从c#中的数据集绑定后,在combobox中插入项

我必须在数据集绑定combobox之后在顶部插入“选择”。我尝试了这个但它不起作用。显示错误“数据集没有任何铸造定义”。我想我没有正确使用它。评论代码是我尝试但不工作的部分。

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

您必须插入要数据绑定的对象而不是combobox。 您无法直接插入combobox。

你可以用这个:

 DataTable dt = new DataTable(); dt.Columns.Add("ID", typeof(int)); dt.Columns.Add("CategoryName"); cmbCategory.DisplayMember = "CategoryName"; cmbCategory.ValueMember = "ID"; cmbCategory.DataSource = dt; DataRow dr = dt.NewRow(); dr["CategoryName"] = "Select"; dr["ID"] = 0; dt.Rows.InsertAt(dr, 0); cmbCategory.SelectedIndex = 0; 

这是一个非常直截了当的例子。

将项目绑定到数据源后,无法将项目添加到ComboBox 。 要使用绑定数据源从ComboBox添加或删除项目,您必须通过数据源本身来完成。

您可以将DataRow插入到表中,它将自动添加到您的ComboBox 。 请尝试以下方法:

  DataRow dr = dsCat.Tables[0].NewRow(); dr["CategoryName"] = "Select"; dr["ID"] = 123;// Some ID dsCat.Tables[0].Rows.Add(dr); 
 // cmbCategory.DataSource =(new object[] { "Select" }).Concat(this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType).Cast()); 

你可能能够做到这一点,但你的语法在某种程度上是错误的。

也许你可以将它拆分,直到你搞清楚,然后将其压缩回内联函数。

 List  catData = new List  { "Select" }; DataSet catByType = this.liveReportingDalc.GetCategoriesByType(CategoryType.RegistrationType); foreach(DataRow oRow in catByType.Tables[0].Rows) { catData.Add(oRow.ItemArray[0]); } 

但要实现这一点,您需要巩固对从GetCategoriesByType函数返回的数据的理解。 对象是否会像“选择”这样的文字?