【发布时间】:2015-05-12 04:35:46
【问题描述】:
我是 WPF 的新手。我正在尝试从数据库加载值以填写CheckedListBox。根据条件,某些项目在加载到checkedlistbox 时必须设置为已选中。
这该怎么做?我试过下面的代码,项目被加载到CheckedListBox,但没有被检查。
下面是加载到选中列表框的值
public void fillcheck()
{
con = new SqlConnection(connectionstring);
con.Open();
string comboquery = "SELECT [Machine] FROM Department Where active='True'";
SqlCommand cmd = new SqlCommand(comboquery, con);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string fil1 = rdr.GetString(0);
Checkedlistbox1.Items.Add(fil1);
}
rdr.Close();
}
int departmentID=60//for just refer
Object[] jobs = CheckedlistBox1.Items.Cast<Object>().ToArray();
foreach (Object obj in jobs)
{
string query = "SELECT [Machine] FROM Department Where ID='" + departmentID+ "'";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
string mac = rdr.GetString(0);//Here i get two values(XRAY,CT)but finally shown CT only be checked,so how to do both checked
if (mac == obj.ToString())
{
int indexx = CheckedlistBox1.Items.IndexOf(mac);
if (indexx >= 0)
{
CheckedlistBox1.SetItemChecked(indexx, true);
}
}
}
rdr.Close();
}
【问题讨论】:
-
可能您想迭代 chlstBox.Items 中的所有项目而不是 chlstBox.CheckedIndices?
-
是的,值已加载到checkedlistbox中,但根据我上面提到的情况,我无法检查
-
您应该使用 code-foreach (int indexChecked in chlstBox.Items) 而不是 foreach (int indexChecked in chlstBox.CheckedIndices)。开始时,您有 0 个选定项目。
标签: c# sql-server wpf foreach checkedlistbox