我在窗体上加入了checklistBox,想把数据库中某表的一列加进来 运行倒是没错误 但是checklistbox上什么都没有
代码如下:
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{ SqlConnection myConnection = new SqlConnection("Data Source=WH\\SQLEXPRESS;Initial Catalog=FinanceDB;Integrated Security=True");
myConnection.Open();
string str = "select * from WorkDiary";
SqlDataAdapter sql = new SqlDataAdapter(str, myConnection);
DataTable dt = new DataTable();
sql.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i<= dt.Rows.Count-1; i++)
{
checkedListBox1.Items.Add("" + dt.Rows[i]["CustomerID"].ToString() );
}
}
myConnection.Close();
}
可是你的checkboxlist项有没有改变呢?
如果没有改变,你上面的代码就没有执行。
{
SqlConnection myConnection = new SqlConnection("Data Source=WH\\SQLEXPRESS;Initial Catalog=FinanceDB;Integrated Security=True");
myConnection.Open();
string str = "select * from WorkDiary";
SqlDataAdapter sql = new SqlDataAdapter(str, myConnection);
DataTable dt = new DataTable(); sql.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
checkedListBox1.Items.Add("" + dt.Rows[i]["CustomerID"].ToString());
}
}
myConnection.Close();
}然后在你的窗口载入时调用private void form1_Load(object sender, EventArgs e)
{
into_CheckListBoxValues();
}
新手没关系,先下个例子看看别人如何做。
多动手。
事实上,CheckedListBox像ListBox一样有DataSource属性,DisplayMember和ValueMemeber属性也都是有的,只是IntelliSense不能将其智能感知出来。
因此,我们可以通过代码将CheckedListBox绑定.
checkedListBox1.DataSource=dt;
checkedListBox1.DisplayMember="CustomerID";
{
ListItem item =new ListItem();
item.text=......
item.value=......
checkedListBox1.Items.Add(item);
}
{
SqlConnection myConnection = new SqlConnection("Data Source=WH\\SQLEXPRESS;Initial Catalog=FinanceDB;Integrated Security=True");
myConnection.Open();
string str = "select * from WorkDiary";
SqlDataAdapter sql = new SqlDataAdapter(str, myConnection);
DataTable dt = new DataTable(); sql.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("有数据");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
checkedListBox1.Items.Add("" + dt.Rows[i]["CustomerID"].ToString());
}
}
myConnection.Close();
}
晕了:注意我红色的地方,把你的代码改成上面的,
如果运行后,看看是否弹出对话框。
如果没有,就证明你没有查出数据。