views:

1384

answers:

4

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?

+4  A: 

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).

Fredrik Mörk
thank you solved
Nagu
A: 

I think you'd have to add it to the underlying datatable (ds.Tables["emp"]) for it to appear as an entry in the list when you're using databound controls.

CodeByMoonlight
A: 

When your control is data bound you cannot add items manually I think.

To work around this problem you could either add a new item to your data source, or you could add the items manually.

Rune Grimstad
A: 

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/

Kevin Coulombe