[英]How to retrieve data from database to CheckedListBox and set the items as checked?
我是WPF的新手。 我正在嘗試從數據庫中加載值以填充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();
}
您需要將SqlDataReader rdr
內容傳輸到DataTable
。 這將幫助您獲得一個包含多個行的DataTable對象,如上所述。
現在進行下一步,您可以在該DataTable
對象上應用一個foreach
來遍歷其所有行,如下所示:
foreach(DataRow dr in dt.Rows)
{
if(yourCondition)
{
//set isChecked = true for the checkbox.
}
}
更新:
嘗試像這樣修改while
循環:
while (rdr.Read())
{
string mac = rdr.GetString(0);
ListItem li = new ListItem();
li.Value = "yourBindedValue";// some value from database column
li.Text = "yourBindedText";// use mac if its text.
int index = Checkedlistbox1.Items.IndexOf(li);
if (index >= 0)
{
Checkedlistbox1.SetItemChecked(index, true);
}
}
我已經對此進行了測試,並且可以正常工作。 您只需要在li
對象中傳遞要查找的CheckBoxListItem的Text
和Value
,就可以獲取索引(如果存在)。 確保同時傳遞兩個屬性。
您應該使用以下代碼-
foreach (int indexChecked in chlstBox.Items)
代替
foreach (int indexChecked in chlstBox.CheckedIndices)
開始時,您有0個選定項,這就是為什么您的外部for循環無法正常工作的原因。
編輯-
基本邏輯也不正確。 您應該遍歷數據集,在復選框列表中找到字符串,然后進行檢查。 因此,不需要外部foreach循環。 另外,請確保使用正確的checkboxlist變量。 在for循環中,您正在使用chlstBox ,而在搜索時,您正在使用Checkedlistbox1 ...。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.