(Using C# Visual Studio 2015, Windows Forms)
I have a list of strings that I want to show in a DataGridView (DGV).
Each row in the DGV will have:
- column[0]: String value from list (ColumnType: DataGridViewTextBoxColumn)
- column[1]: A blank cell (user will enter data here) (ColumnType: DataGridViewTextBoxColumn)
- column[2]: A ComboBox (ColumnType: DataGridViewComboBoxColumn)
Every ComboBox in each record will have identical items (the same DataSet) and I retrieve these from a SQL query to my Access Database (accdb).
My main problem is that I need to identify the ValueMember
and DisplayMember
of each ComboBox, and I can't figure out how to do that. My current code just tries to copy the DataTable results
into the ComboBox, but I'm getting the error:System.ArgumentException.DataGridViewComboBoxCell value is not valid.
And it repeats for every value of every ComboBox in the DataGridView. I cannot figure out what I'm doing wrong.
Any help would be greatly appreciated. Here's the code:
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);
}
EDIT: I just checked to see if my query was pulling records by adding this line:
MessageBox.Show(results.Rows.Count.ToString());
And I received the correct number of records