vatsal
vatsal

Reputation: 309

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

Upvotes: 18

Views: 53636

Answers (4)

Adil
Adil

Reputation: 148110

You can use dsCat.Rows.Add method.

dsCat.Rows.Add(0, "Other"); // this will add row
cmbCategory.DataSource = dsCat.Tables[0];
cmbCategory.DisplayMember = "CategoryName";
cmbCategory.ValueMember = "ID";

Upvotes: 0

Vishal Suthar
Vishal Suthar

Reputation: 17183

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.

Upvotes: 29

Asif Mushtaq
Asif Mushtaq

Reputation: 13150

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

Upvotes: 8

Andyz Smith
Andyz Smith

Reputation: 708

// cmbCategory.DataSource =(new object[] { "Select" }).Concat(this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType).Cast<object>()); 

You might be able to do this, but your syntax is wrong somehow.

Maybe you can split it up until you figure it out and then compress it back into in-line functions.

List <object> catData = new List <object> { "Select" };

DataSet catByType = this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType);

foreach(DataRow oRow in catByType.Tables[0].Rows)
{ catData.Add(oRow.ItemArray[0]); }

But for this to work you need to consolidate your understanding of the data coming back from the GetCategoriesByType function. Will the objects be text like "Select"?.

Upvotes: 0

Related Questions