这是一个代码,我从datatable向datagridview添加值。 datagridview的“First”和“Third”列已填充数据表中的数据。问题出在“第二”和“第四”列,因为我必须将其作为组合框供用户选择。每个组合框都有默认值“columnDefaultValue”。
string sqlMatchedData = "SELECT colA, colB, colC, colD " +
"FROM TB_LOOKUP_COLUMN "
ds = databaseManager.GetData(sqlMatchedData);
dataGridView1.ColumnCount = 4;
dataGridView1.Columns[0].Name = "First";
dataGridView1.Columns[1].Name = "Second";
dataGridView1.Columns[2].Name = "Third";
dataGridView1.Columns[3].Name = "Forth";
foreach(DataRow row in ds.Tables[0].Rows)
{
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells[0].Value = row[0].ToString();
dataGridView1.Rows[n].Cells[2].Value = row[3].ToString();
string columnDestination = row[1].ToString();
string columnType = row[2].ToString();
comboboxDestinationColumn(columnDefaultValue);
}
如何使用数据表创建组合框并将其绑定到特定单元格?
private void comboboxDestinationColumn(string columnDefaultValue)
{
string sqlLookupColumn = "SELECT colALookUp, colBLookUp FROM TB_LOOKUP_COLUMN";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn();
combo.HeaderText = "Destination";
combo.Name = "combo";
foreach(DataRow row in dsColumn.Tables[0].Rows)
{
//populate combobox with data from datatable with defaul value columnDefaultValue
}
}
EDITED
我找到了将组合框添加到datagridview的方法。但我仍然缺乏如何基于变量 columnDefaultValue
为每个组合框设置默认值的方法private void comboboxDestinationColumn(string columnDefaultValue, int n)
{
string sqlLookupColumn = "SELECT colALookUp, colBLookUp FROM TB_LOOKUP_COLUMN";
DataSet dsColumn = databaseManager.GetData(sqlLookupColumn);
DataGridViewComboBoxCell comboboxColumn = new DataGridViewComboBoxCell();
foreach (DataRow row in dsColumn.Tables[0].Rows)
{
comboboxColumn.Items.Add(row[1].ToString());
}
dataGridView1.Rows[n].Cells[1] = comboboxColumn;
}
我试图找到类似的东西:
comboboxColumn.Selected = true;
这样做的正确方法是什么?
答案 0 :(得分:0)
您只需在创建后设置组合单元的值即可。就像在foreach循环之后,你应该放comboboxColumn.Value = comboboxColumn.Items[0] //or whichever of all the items you want
。这会给你的组合框提供所需的价值。
P.S。:将DataGridViewComboBoxCell
命名为“comboboxColumn”是一个不好的实践......