Question

Originaly posted a while back on a different forum, hope I can find a bit more help here :)

Hi Guys,

I'm sure this is a pretty basic question, but I'm new to much programming and C#. I find I need to clear databindings on several controls and currently have:

            lblTableValue1.DataBindings.Clear();
            lblTableValue2.DataBindings.Clear();
            lblTableValue3.DataBindings.Clear();
            lblTableValue4.DataBindings.Clear();
            lblTableValue5.DataBindings.Clear();
            lblTableValue6.DataBindings.Clear();
            lblTableValue7.DataBindings.Clear();

This can't be the best way of doing this can it? I also need to set all these text values to "", can I group them in someway and call clear on the whole group?

Many Thanks in advance G

Was it helpful?

Solution

foreach(Control c in this.Controls)
{
    if(c.Name.StartsWith("lblTableValue"))
    {
        c.DataBindings.Clear();
    }
}

That might do the job. Or if you're more of a purist:

foreach(Control c in new Control[]
    {
        lblTableValue1,
        lblTableValue2,
        etc
    })
{
    c.DataBindings.Clear();
}

OTHER TIPS

In this sort of scenario, I find it best to include the controls I want to manipulate, in some sort of container, say a Panel. Then iteration becomes easy:

private void SetLabelText() 
{ 
  foreach (Control c in Panel1.Controls) 
  { 
    if (c is Label && c.ID.StartsWith("lblTableValue"))
    { 
      Label lbl = c as Label; 
      lbl.Text = string.Empty;
      lbl.DataBindings.Clear();
    } 
  } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top