Nathan
Nathan

Reputation: 1143

DataBindings on a checkbox

I am currently pulling data from one of my SQL Databases into my application. I can get it working for my text boxes and other items, however, I can not seem to get it to work for a checkbox. Here is the code I am using:

DataTable dt = new DataTable("dt");
using (SqlConnection sqlConn = new SqlConnection(@"Connection Stuff;"))
{
    using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Box WHERE id = " + txtID.Text, sqlConn))
    {
        da.Fill(dt);
    }
}
Title.DataBindings.Add("text", dt, "title");
Picture.DataBindings.Add("text", dt, "image");
Side.DataBindings.Add("text", dt, "side");
Content.DataBindings.Add("text", dt, "content");
Check.DataBindings.Add(I dont know what to do here);

The data that is stored in the database when the checkbox is checked vs. unchecked is 0 and 1 respectivly. How would I set it to checked when the application loads if the value in the database is 1 and unchecked when it is 0?

I have tried the following:

Store the 0 or 1 in a textbox and use the following if statement:

Check.DataBindings.Add("text", dt, "check");
if (txtCheckValue.Text == 1)
{
    Check.Checked = true;
}

This way works but I was wondering if there is a more efficient way to do this. Hopefuly following the same Thing.DataBindings.Add() format, reason being that I do not want my application to have lots of hidden text boxes.

Upvotes: 4

Views: 23189

Answers (2)

Robert K.
Robert K.

Reputation: 111

Try

Check.DataBindings.Add("Checked", dt, "check");

The first parameter is the property of the control, so instead of "Text", you want "Checked".

This is correct. But the one thing you need to know (which took me half an hour just now), the checkbox needs to validate (with the default setting). So it needs to lose focus for example.

So I found the better solution would be:

Check.DataBindings.Add("Checked", dt, "check", false, DataSourceUpdateMode.OnPropertyChanged);

Upvotes: 11

LarsTech
LarsTech

Reputation: 81620

Try

Check.DataBindings.Add("Checked", dt, "check");

The first parameter is the property of the control, so instead of "Text", you want "Checked".

Upvotes: 8

Related Questions