Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert item in combobox after binding it from a Dataset in c#

I have to insert "Select" at top after combobox is bound from dataset.i tried this but it isn't working.Throws error "dataset doesn't have any definition for cast".I think i am not using it properly.Commented code is the part i tried but not working.

cmbCategory.DataSource = dsCat.Tables[0];
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
// cmbCategory.Items.Add("Select");
// cmbCategory.SelectedText = "Select";
// cmbCategory.DataSource =(new object[] { "Select" }).Concat(this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType).Cast<object>()); 
like image 759
vatsal Avatar asked Jul 07 '12 12:07

vatsal


People also ask

Which method is used to add items in a ComboBox c1?

An entire array can be added to the ComboBox by using the AddRange method to add the object or string of items to the C1ComboBox. To add items to the C1ComboBox using the Add method of the C1ComboBox class.

Which method is used to add items in ComboBox?

To add a set of items to the combo box it is best to use the AddRange method. If you choose to use the Add method to add a number of items to the combo box, use the BeginUpdate method to suspend repainting during your add and the EndUpdate method to resume repainting.

How do you bind a ComboBox?

To bind a ComboBox or ListBox control If you are binding to a table, set the DisplayMember property to the name of a column in the data source. If you are binding to an IList, set the display member to a public property of the type in the list.


2 Answers

You have to Insert to the object you are databinding to rather than to the combobox. You can't insert directly into the combobox.

You can use this:

DataTable dt = new DataTable();

dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("CategoryName");

DataRow dr = dt.NewRow();
dr["CategoryName"] = "Select";
dr["ID"] = 0;

dt.Rows.InsertAt(dr, 0);

cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";
cmbCategory.DataSource = dt;
cmbCategory.SelectedIndex = 0;

This is very straight forward example.

like image 71
Vishal Suthar Avatar answered Oct 17 '22 18:10

Vishal Suthar


You cannot add items to a ComboBox after binding it to a data source. To add or remove items from a ComboBox with a bound data source, you have to do it through data source itself.

You can insert a DataRow into your table and it will be automatically added to your ComboBox. Try the following:

 DataRow dr = dsCat.Tables[0].NewRow();
 dr["CategoryName"] = "Select";
 dr["ID"] = 123;// Some ID
 dsCat.Tables[0].Rows.Add(dr);
like image 8
Asif Mushtaq Avatar answered Oct 17 '22 17:10

Asif Mushtaq