這是一個代碼,我從datatable中爲datagridview添加值。 datagridview的「第一個」和「第三個」列已經填充了數據表中的數據。問題在於「第二」和「第四」列,因爲我必須使它成爲供用戶選擇的組合框。每個組合框的默認值是「columnDefaultValue」。如何從數據表添加combobox到datagridview?
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;
什麼正確的方法來做到這一點?
WebForms?的WinForms? WPF? ASP.NET MVC? SilverLight的? –
@UweKeim winforms先生 – MRu
爲什麼不創建它後創建組合框的值。就像在foreach循環之後,你應該使它成爲'comboboxColumn.Value = comboboxColumn.Items [0] //或者你想要的所有項目中的任何一個。 P.S .:這是一個不好的實踐,命名一個'DataGridViewComboBoxCell'就像「comboboxColumn」... –