DataGridView set column cell Combobox
Try this
dataGridView1.AutoGenerateColumns = false;
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(String));
dt.Columns.Add("Money", typeof(String));
dt.Rows.Add(new object[] { "Hi", 100 });
dt.Rows.Add(new object[] { "Ki", 30 });
DataGridViewComboBoxColumn money = new DataGridViewComboBoxColumn();
var list11 = new List<string>() { "10", "30", "80", "100" };
money.DataSource = list11;
money.HeaderText = "Money";
money.DataPropertyName = "Money";
DataGridViewTextBoxColumn name = new DataGridViewTextBoxColumn();
name.HeaderText = "Name";
name.DataPropertyName = "Name";
dataGridView1.DataSource = dt;
dataGridView1.Columns.AddRange(name, money);
Just use DataPropertyName
instead of ValueMember
You could try the following:
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.Name = "Money";
column.DataSource = new string[] { "10", "30", "80", "100" };
dataGridView1.Columns.Add(column);
for (int row = 0; row < dataGridView1.Columns.Count; row++)
{
DataGridViewComboBoxCell cell =
(DataGridViewComboBoxCell)(dataGridView1.Rows[row].Cells["Money"]);
cell.DataSource = new string[] { "80", "100" };
}
Or this:
foreach (DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(row.Cells["Money"]);
cell.DataSource = new string[] { "10", "30" };
}
You were almost done.
There are only two minor issues:
- In your table you are adding to rows "Money" value as integers, while in your column they are defined as string
- First add your table ad DataGridView DataSource, and then set column DataPropertyName
Full code below:
var table = new DataTable();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Money", typeof(string));
table.Rows.Add("Hi", "100");
table.Rows.Add("Ki", "30");
var column = new DataGridViewComboBoxColumn();
column.DataSource = new List<string>() { "10", "30", "80", "100" };
dataGridView1.Columns.Add(column);
dataGridView1.DataSource = table;