![](/img/trans.png)
[英]set DataGridView ComboBoxColumn selectedIndex from DataGridView BindingSource
[英]Set Value of ComboBoxColumn DataGridView
我有個問題。 我有一個ComboBoxColumn
並希望通過ComboBox
變量在此Column
中填充數據庫中的數據。 我怎樣才能做到這一點。
我試過的這個片段不起作用
ComboBoxColumn.Items.AddRange("One", "Two", "Three", "Four");
我的問題是我在另一個 function 中獲取數據,它將保存 ComboBox 變量中的所有值(每個函數都可以訪問),我想通過 Column-/Row-Index 填充 DataGridView 中的單元格,如下所示:
private ComboBox ComboBoxItems
private void datagridview_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
int col1 = datagridview.Columns["datagridview_col1"].Index;
int col2 = datagridview.Columns["datagridview_col2"].Index;
int col3 = datagridview.Columns["datagridview_col2"].Index;
if ((e.ColumnIndex == col1))
{
fill_col2();
}
else if ((e.ColumnIndex == col2))
{
datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ComboBoxItems1;
foreach (var item in ComboBoxItems1.Items)
{
Console.WriteLine(ComboBoxItems1.Items.Count);
Console.WriteLine(item.ToString());
}
if (!String.IsNullOrEmpty(section))
{
fill_col3();
}
}
else if ((e.ColumnIndex == col3))
{
datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ComboBoxItems2;
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading Data!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
有沒有人想出一個好的工作解決方案?
如果要設置 ComboboxColumn 數據源,可以在定義 ComboboxColumn 時進行設置。
var ComboCol= new DataGridViewComboBoxColumn
{
HeaderText = "ComboCol",
Name = "ComboCol",
DataSource = new List<string> {"One", "Two", "Three", "Four"}
};
然后在使用數據庫中的數據填充 combobox 之前,您需要先將單元格轉換為DataGridViewComboBoxCell
。
DataSet ds;
string connetionString = @"Connection String";
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From TestTable", conn);
ds = new DataSet();
sda.Fill(ds, "TableName");
}
DataGridViewComboBoxCell ComboCell;
foreach (DataRow row in ds.Tables[0].Rows)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["CommonCol1"].Value = row[0];
ComboCell= (DataGridViewComboBoxCell)(dataGridView1.Rows[index].Cells["ComboCol"]);
ComboCell.Value = row[1].ToString();
}
希望這可以幫到你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.