Hi here i want to bind some values to check box dynamically.
dataset ds = //getting emp values form database;
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];
it is working fine. But i want to add
"Select emplyoee" as a default value of check box .
But my check box directly adding values like
a1
a2
a3
like this.
I tried like this
cbemp.Items.Insert(0, "Select emplyoee");
but it is not working
how can i add it?
When you use databinding, you cannot "manually" add or remove items. The only way to achieve what you want using databinding is to insert a row first in the DataTable
with the desired value, or to populate the combobox by code (add the "Select employee" item and then iterate of the the DataTable
rows to add the records).
Perhaps something like this could work:
// create new row for "Select employee"
DataRow row = ds.Tables["emp"].NewRow();
row["empid"] = -1;
row["empname"] = "Select employee";
// insert the row at the top of the table
ds.Tables["emp"].Rows.InsertAt(row, 0);
// do the databinding
cbemp.ValueMember = "empid";
cbemp.DisplayMember = "empname";
cbemp.DataSource = ds.Tables["emp"];
I don't use databinding much, so there may be drawbacks with this that I am unaware of (but I am confident that the community will point that out in that case).
Inserting data in your data source is a bad idea. It promotes breaking your layers' abstractions and may lead to some issues if you are using the same data source elsewhere.
Instead, you can easily extend the ComboBox to show a "Please select" message when it has no item selected.
I blogged about this issue and provided the code here : http://www.byteauthor.com/2010/08/inner-label-in-combobox/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With