[英]Winforms : How to bind the Checkbox item of a CheckedListBox with databinding
我在一個表單中有一個databinded checkedlistbox,我想知道是否甚至可以使用對象的某個屬性對每個列表框項的復選框進行數據綁定。
在此先感謝您的任何幫助:)
編輯:也許我的問題被誤解了。
我想知道是否可以對CheckedListBox的每個項目的復選框進行數據綁定。 我知道如何數據綁定到源以及如何通過迭代itmes以編程方式更改條目。 我不知道的是,是否有可能有一個實現INotifyPropertyChanged的類,以便當“CheckedState”屬性更改時CheckedListBox更新自身。
根據Samich的回答,這是一個完整的例子,綁定源是一個Object
private void Form1_Load(object sender, EventArgs e)
{
List<randomClass> lst = new List<randomClass>();
lst.Add(new randomClass());
lst.Add(new randomClass());
lst.Add(new randomClass());
lst.Add(new randomClass());
lst.Add(new randomClass());
lst.Add(new randomClass());
((ListBox)this.checkedListBox1).DataSource = lst;
((ListBox)this.checkedListBox1).DisplayMember = "Name";
((ListBox)this.checkedListBox1).ValueMember = "IsChecked";
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
randomClass obj = (randomClass)checkedListBox1.Items[i];
checkedListBox1.SetItemChecked(i, obj.IsChecked);
}
}
}
public class randomClass
{
public bool IsChecked { get; set; }
public string Name { get; set; }
public randomClass()
{
this.IsChecked = true;
Name = "name1";
}
}
randomClass
用於演示目的
你可以在這里找到答案: 在CheckBoxList中使用數據源
var checkBoxList = (ListBox)MyCheckBoxList;
checkBoxList.DataSource = dataSource;
checkBoxList.DisplayMember = "name";
checkBoxList.ValueMember = "enabled";
確保ValueMember
的類型為bool
。
我剛剛得到了如何將sql中的表數據化為一個沒有壓力的checkboxlist。 我很高興分享它。 我手動添加了它們......
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
conn.ConnectionString = "Data Source=MICMIKE\\SQLEXPRESS;Initial Catalog=Enterprise;Integrated Security=True";
conn.Open();
string query = "Select Position from Position";// position column from position table
cmd.Connection = conn;
cmd.CommandText = query;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string myItem = dr["Position"].ToString();
checkedListBox1.Items.Add(myItem, true);//true means check the items. use false if you don't want to check the items or simply .....Items.Add(myItem);
}
要訪問核對表列表中選中的項目,請使用
foreach(object item in Checkedlistbox1.CheckedItems)
{
string itemchecked = item.ToString();
MessageBox.Show(itemchecked);// This will show all the checked items in the checklistbox.
}
它確實有效。 我現在就明白了。 我希望你喜歡它!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.