DataBindings on a checkbox

六月ゝ 毕业季﹏ 提交于 2020-06-28 05:40:46

问题


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.


回答1:


Try

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

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




回答2:


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);


来源:https://stackoverflow.com/questions/11656613/databindings-on-a-checkbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!