如何在 C# 中的 DataGridView 中特定列的每个单元格中添加下拉列表



我正在尝试在我的Winforms应用程序中的数据网格视图中的列的所有单元格中添加一个下拉列表。我通过将 dgv 拖到窗体中并在创建类时添加列来以编程方式创建视图。

下拉列表出现在我的 DGV 列中,但是当我单击列表时,没有任何内容打开 - 我不确定 ComboBox 是否已填充且未打开,或者它是否根本不包含供用户选择的值。将 comboBox 添加到单元格时将鼠标悬停在对象上,我可以看到用我的值填充的项目数组。

请告知我如何允许用户选择从我的列表中填充的单元格中的值

DataGridViewTextBoxColumn diffKey = new DataGridViewTextBoxColumn();
DataGridViewComboBoxColumn matchDesc = new DataGridViewComboBoxColumn();
DataGridViewTextBoxColumn permDiff = new DataGridViewTextBoxColumn();
grdEditAnnot.Columns.Add(diffKey);
grdEditAnnot.Columns.Add(matchDesc);
grdEditAnnot.Columns.Add(permDiff);
DataGridViewComboBoxCell matchDescDropbox = new DataGridViewComboBoxCell();
List<string> lstMatchDesc = new List<string>();
LoadMatchDescriptions(out lstMatchDesc);

foreach (string ddlItem in lstMatchDesc)
{
matchDescDropbox.Items.Add(ddlItem);
}
grdEditAnnot.Rows.Add(2);

matchDescDropbox.DataSource = GetMatchDescDDL(); // Bind combobox with datasource.  
matchDescDropbox.ValueMember = "Description";
matchDescDropbox.DisplayMember = "Description";
grdEditAnnot.Rows[0].Cells[1] = matchDescDropbox;
}
private DataTable GetMatchDescDDL()
{
DataTable l_dtDescription = new DataTable();
l_dtDescription.Columns.Add("Description", typeof(string));
List<string> matchDescLst;
if (LoadMatchDescriptions(out matchDescLst) == 0)
{
foreach(string matchDesc in matchDescLst)
{
l_dtDescription.Rows.Add(matchDesc);
}
}
return l_dtDescription;
}
private int LoadMatchDescriptions(out List<string> matchDscLst)
{
//string SQL = SQL USED TO POPULATE MY LIST 
//a temporary list of test strings would work to show how to get this to work... ex: list of test1, test2, test3 etc 

try
{
matchDscLst = new List<string>();
rdr.ExecuteSQL(SQL);
while ((rec = rdr.FetchNextRecord()) != null)
{
matchDscLst.Add(rec.GetStringVal(0));
}
return 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error Loading Match Descriptions", MessageBoxButtons.OK, MessageBoxIcon.Error);
matchDscLst = new List<string>();
return -1;
}
}

这是我在StackOverflow上的第一篇文章;如果这不是最好的格式,或者我们需要更多信息,我们深表歉意。

代码结果: 创建的网格;用户无法打开组合框或在文本框列中键入

内容

使用DataGridViewComboBoxCell

看这个例子: https://www.aspsnippets.com/Articles/Add-ComboBox-to-DataGridView-in-Windows-Forms-Application-using-C-and-VBNet.aspx

最新更新