Kia Boluki
Kia Boluki

Reputation: 325

Why I can't bind label's tag to sql data?

I am trying to use Label's Tag for editing it's Text property. I want to bind Label's Tag to a data member and change it to define Label's Text.

I Create a new Binding like this:

//
//Create Label For JoinDate Content
//
Label lblJDC = new UniLib_Label();
lblJDC.TextAlign = ContentAlignment.MiddleLeft;

lblJDC.DataBindings.Add(new Binding("Tag", CurrentUserDataBindingSource, "PersonJoinDate"));
if (lblJDC.Tag != null)
{
     DateTime joinDate = Convert.ToDateTime(lblJDC.Tag);
     lblJDC.Text = new dateFunctions().shamsi(joinDate);
}
lblJDC.Location = new Point(280, 0);
lblJDC.AutoSize = true;
grp.Controls.Add(lblJDC);

But I get null value for Tag and when I try this code for Text it is ok and I get the correct value.

What is the problem?

Upvotes: 2

Views: 129

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125342

The data binding will work when you add the control in visible state to the form.
Once you setup data binding with this conditions, it will continue working even if the control goes invisible.

The below code will work as expected and shows the value of data field:

var label = new Label();
label.DataBindings.Add(new Binding("Tag", yourBindingSource, "DataField"));
var panel = new Panel();
panel.Controls.Add(label);
this.Controls.Add(panel);
MessageBox.Show(string.Format("{0}", label.Tag));

If you comment panel.Controls.Add(label); or comment this.Controls.Add(panel);or set the visible property of panel or label to false before adding the control to form, it will not work.

Upvotes: 1

Related Questions