I'm populating a combobox from a datatable with the following code:
public void PopulateCategoryCbo()
{
string connString = string.Format(<connectionString>);
NpgsqlConnection conn = new NpgsqlConnection(connString);
conn.Open();
string query = "SELECT id, category FROM categories ORDER BY category";
NpgsqlCommand cmd = new NpgsqlCommand(query, conn);
NpgsqlDataReader reader;
reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
//DataRow row = dt.NewRow();
//row["id"] = 0;
//row["category"] = "All Categories";
//dt.Rows.InsertAt(row, 0);
dt.Columns.Add("id", typeof(string));
dt.Columns.Add("category", typeof(string));
dt.Load(reader);
cboSelectCategory.ValueMember = "id";
cboSelectCategory.DisplayMember = "category";
cboSelectCategory.DataSource = dt;
conn.Close();
}
The four commented lines are my attempt at adding to the top of the datatable an "All Categories" row with an index of 0. I did that code per this SO question and answer.
However, when I run the solution, it breaks at the row["id"] = 0;
line with the message, 'Column "id" does not belong to table.'
I tried using 0 and 1, thinking they would refer to the index value of the columns, but I got the message 'Column 0 does not belong to table.'
I'm not understanding why this isn't working. I see a lot of similar solutions when I Google this issue.