Hi,
If only bind the datasource to the class, there is no data in the class and also set the DataPropertyName, it will throw an error. This is because the combobox can’t find the corresponding displayvalue in the datasource.
I wrote the following example for you.
I create two bindinglists as the DataGridView datasource and ComboboxColumn datasource. You need to make sure the corresponding datasouce of comboboxcolumn.valuemember contains the bound datavalue of comboboxcolumn. Otherwise it will throw an error.
private void Form1_Load(object sender, EventArgs e)
{
BindingList<Customer> customList = new BindingList<Customer>();
customList.Add(new Customer(1, 1, "aa"));
customList.Add(new Customer(2, 1, "bb"));
customList.Add(new Customer(3, 2, "cc"));
customList.Add(new Customer(4, 1, "dd"));
BindingList<GenderDetial> genderList = new BindingList<GenderDetial>();
genderList.Add(new GenderDetial(1, "male"));
genderList.Add(new GenderDetial(2, "female"));
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = customList;
DataGridViewTextBoxColumn txtID = new DataGridViewTextBoxColumn();
txtID.DataPropertyName = "Id";
txtID.Name = "ID";
txtID.HeaderText = "Custom ID";
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.DataPropertyName = "GenderID";
cmb.Name = "Gender";
cmb.HeaderText = "Gender";
cmb.DataSource = genderList;
cmb.ValueMember = "GenderID";
cmb.DisplayMember = "Gender";
DataGridViewTextBoxColumn txtName = new DataGridViewTextBoxColumn();
txtName.DataPropertyName = "Name";
txtName.Name = "Name";
txtName.HeaderText = "Custom Name";
dataGridView1.Columns.AddRange(txtID, cmb, txtName);
}
}
public class Customer
{
private int _id;
private int _genderID;
private string _name;
public Customer(int customID, int customGenderID, string customName)
{
this.Id = customID;
this.GenderID = customGenderID;
this.Name = customName;
}
public int Id
{
get { return _id; }
set { _id = value; }
}
public int GenderID
{
get { return _genderID; }
set { _genderID = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
}
public class GenderDetial
{
private int _genderID;
private string _gender;
public GenderDetial(int id, string genderDetial)
{
this.GenderID = id;
this.Gender = genderDetial;
}
public int GenderID
{
get { return _genderID; }
set { _genderID = value; }
}
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
}
Best regards,
Ling Wang
Please remember to click “Mark as Answer�on the post that helps you, and to click “Unmark as Answer�if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.