如何从datatable向datagridview添加组合框?
本文关键字:添加 组合 datagridview datatable | 更新日期: 2023-09-27 17:51:21
这是一个代码,我从datatable添加值到datagridview。datagridview的"第一"answers"第三"列已经填充了来自数据表的数据。问题是"第二"answers"第四"列,因为我必须让它成为一个组合框供用户选择。每个组合框都有默认值"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
}
}
编辑
我找到了将组合框添加到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;
正确的方法是什么?
您可以在创建comboboxcell后设置它的值。就像foreach循环之后,你应该把comboboxColumn.Value = comboboxColumn.Items[0] //or whichever of all the items you want
放进去。这将给你的组合框想要的值。注:将DataGridViewComboBoxCell
命名为"comboboxColumn"是一个不好的做法…