【发布时间】:2017-02-13 17:01:27
【问题描述】:
(使用 C# Visual Studio 2015,Windows 窗体)
我有一个要在 DataGridView (DGV) 中显示的字符串列表。
DGV 中的每一行都有:
- column[0]: 列表中的字符串值 (ColumnType: DataGridViewTextBoxColumn)
- column[1]:空白单元格(用户将在此处输入数据)(ColumnType:DataGridViewTextBoxColumn)
- column[2]: 一个 ComboBox (ColumnType: DataGridViewComboBoxColumn)
每条记录中的每个 ComboBox 都将具有相同的项目(相同的数据集),我将这些项目从 SQL 查询中检索到我的 Access 数据库 (accdb)。
我的主要问题是我需要识别每个 ComboBox 的 ValueMember 和 DisplayMember,但我不知道该怎么做。我当前的代码只是尝试将 DataTable results 复制到 ComboBox 中,但出现错误:System.ArgumentException.DataGridViewComboBoxCell value is not valid.
它对 DataGridView 中每个 ComboBox 的每个值重复。我无法弄清楚我做错了什么。
任何帮助将不胜感激。代码如下:
DataTable results = new DataTable();
//Identify the Connection String
connection.ConnectionString = dbQuery.connStr;
//SQL Statement to retrieve ComboBox Items
string sql = @"SELECT ID, DESCRIP FROM tbl_setpoints_categories ORDER BY DESCRIP ASC";
//Create a new ComboBox (this is for testing purposes)
ComboBox cb = new ComboBox();
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = sql;
OleDbDataReader reader = command.ExecuteReader();
results.Columns.Add("ID", typeof(int));
results.Columns.Add("DESCRIP", typeof(string));
results.Load(reader);
//For testing purposes...
cb.ValueMember = "ID";
cb.DisplayMember = "DESCRIP";
cb.DataSource = results;
if (!reader.IsClosed)
{
reader.Close();
}
}
finally
{
connection.Close();
}
//Loop through the list and add each into an array of objects
//This array will be added as a DataGridView row
foreach (string spName in spList)
{
//My Latest Edit, but still produces same error
DataGridViewComboBoxCell cbCell = new DataGridViewComboBoxCell();
cbCell.ValueMember = "ID";
cbCell.DisplayMember = "DESCRIP";
cbCell.DataSource = results;
//End Latest Edit
object[] row = new object[3];
row[0] = spName.ToString();
row[1] = "";
row[2] = cbCell; //From Latest Edit (was: results)
dataGridView1.Rows.Add(row);
}
编辑:我刚刚检查了我的查询是否通过添加以下行来提取记录:MessageBox.Show(results.Rows.Count.ToString());
我收到了正确数量的记录
【问题讨论】:
标签: c# datagridview combobox