user3322369
user3322369

Reputation: 5

Having Problems populating my checkedListBox

So here's whats happening. when I press the event button1 to retrieve the data from my database it shows System.Data.DataRowView. But when I press the button1 event again it shows the actual result and correct data. I want to know how to fix this in just one click of a button to display actual data

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();
}

Upvotes: 0

Views: 198

Answers (2)

Kaerber
Kaerber

Reputation: 1653

Shouldn't the order of assignment be different?

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

instead of

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

Upvotes: 0

Aftab Ahmed
Aftab Ahmed

Reputation: 1737

try this.. You don't need to execute the query for twice.

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();

}

Upvotes: 1

Related Questions