I'm having a problem with filling a comboxcolumn
in a datagrid view. Here is a brief description of my problem.
I've a combo column in datagrid view named as dgvRightsColumn
and table in SQL named as Rights. I want to fill this combobox of dagaridview with the RightsNames in Rights Table.
DataGridViewComboBoxColumn dgvRightsColumn = new DataGridViewComboBoxColumn();
SqlCommand fillRights = new SqlCommand("SELECT * FROM [Rights]", sqlConnection);
SqlDataReader readerRights = fillRights.ExecuteReader();
while (readerRights.Read())
{
dgvRightsColumn.Items.Add(Convert.ToString(readerRights["RightName"]));
}
readerRights.Close();
Problem : you are just creating the object for DataGridViewComboBoxColumn
but not specifying the actual column to be considered from Gridview as ComboBox that is 3rd column.
Solution : you need to cast
the required column from DataGridview
to the DataGridViewComboBoxColumn
to insert the Items.
Replace This :
DataGridViewComboBoxColumn dgvRightsColumn = new DataGridViewComboBoxColumn();
With This:
DataGridViewComboBoxColumn dgvRightsColumn= dgvTasksRights.Columns[2] as DataGridViewComboBoxColumn;
Note : You are not opening the SqlConnectoion
Object sqlConnection
before Executing the ExecuteReader
command.You need to open it as below :
sqlConnection.Open();
Complete Code:
Try This :
SqlCommand fillRights = new SqlCommand("SELECT * FROM [Rights]", sqlConnection);
sqlConnection.Open();
SqlDataReader readerRights = fillRights.ExecuteReader();
DataGridViewComboBoxColumn dgvRightsColumn= dgvTasksRights.Columns[2] as DataGridViewComboBoxColumn;
while (readerRights.Read())
{
dgvRightsColumn.Items.Add(Convert.ToString(readerRights["RightName"]));
}
readerRights.Close();