[英]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.