tags:

views:

378

answers:

2

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

+3  A: 
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();
}
Quibblesome
+1 for the Purist solution! ;-)
Cerebrus
Behaviour based on the name of a control is always a bit sketchy after all! ;)
Quibblesome
Look like good options to me. However what are your opinions on how this compares with your "container" recommendation below, Cerebrus?
G-
A: 

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();
    } 
  } 
}
Cerebrus