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

前端 未结 3 1450
眼角桃花
眼角桃花 2020-12-03 05:41

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 t

3条回答
  •  悲&欢浪女
    2020-12-03 06:12

    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.

提交回复
热议问题