0

所以这就是发生的事情。当我按下事件button1从我的数据库中检索数据时,它显示System.Data.DataRowView。但是当我button1再次按下该事件时,它会显示实际结果和正确的数据。我想知道如何通过单击一个按钮来显示实际数据来解决这个问题

private void button1_Click(object sender, EventArgs e)
{           
    SqlConnection con = new SqlConnection(@"SQLCONNECTIONSTRING");
    con.Open();
    SqlCommand cmd = new SqlCommand("Select * from tbl_members", con);
    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
    SqlDataReader reader = cmd.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Columns.Add("FullName", typeof(string));
    dt.Load(reader);

    DataSet ds = new DataSet();
    adapter.Fill(ds);
    checkedListBox1.DisplayMember = "FullName";
    checkedListBox1.ValueMember = "FullName";
    checkedListBox1.DataSource = ds.Tables[0];
    checkedListBox1.Enabled = true;
    checkedListBox1.Refresh();

    con.Close();
}
4

2 回答 2

1

试试这个。你不需要执行两次查询。

private void button1_Click(object sender, EventArgs e)
{           
   SqlConnection con = new SqlConnection(@"SQLCONNECTIONSTRING");
   con.Open();
   SqlCommand cmd = new SqlCommand("Select * from tbl_members", con);
   SqlDataAdapter adapter = new SqlDataAdapter(cmd);
   //SqlDataReader reader = cmd.ExecuteReader();
   DataTable dt = new DataTable();
   dt.Columns.Add("FullName", typeof(string));

   DataSet ds = new DataSet();
   adapter.Fill(ds);
   dt=ds.Tables[0];
   checkedListBox1.DisplayMember = "FullName";
   checkedListBox1.ValueMember = "FullName";
   checkedListBox1.DataSource = ds.Tables[0];
   checkedListBox1.Enabled = true;
   checkedListBox1.Refresh();

   con.Close();

}

于 2014-02-18T08:51:45.957 回答
0

分配顺序不应该不同吗?

checkedListBox1.DataSource = ds.Tables[0];
checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";

代替

checkedListBox1.DisplayMember = "FullName";
checkedListBox1.ValueMember = "FullName";
checkedListBox1.DataSource = ds.Tables[0];
于 2014-02-18T09:00:41.453 回答