Reputation: 27
I'm trying to add a combo Box to the datagrid View. This is the code for the datagrid view
SqlDataAdapter da = new SqlDataAdapter("SELECT pid, pdtName, amount, Qty,day, cat from purchase where year=@year and month=@month", ConnectionInfo.con);
da.SelectCommand.Parameters.AddWithValue("@year", comboBox3.Text);
da.SelectCommand.Parameters.AddWithValue("@month", comboBox2.Text);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
this.dataGridView1.Columns[0].HeaderText = "number";
this.dataGridView1.Columns[0].ReadOnly = true;
this.dataGridView1.Columns[0].Visible = false;
this.dataGridView1.Columns[1].HeaderText = "name";
this.dataGridView1.Columns[2].HeaderText = "amount";
this.dataGridView1.Columns[3].HeaderText = "number";
this.dataGridView1.Columns[4].HeaderText = "day";
this.dataGridView1.Columns[5].HeaderText = "category";
for column 5 in the datagrid view I'm trying to set it as a combo box and read the category names from the category table in my database.
I'm starting with this code but I don't know how to complete it
string query = "select distinct cat from purchase ";
SqlDataAdapter da2 = new SqlDataAdapter(query, ConnectionInfo.con);
DataSet ds2 = new DataSet();
da2.Fill(ds2, "purchase");
DataGridViewComboBoxColumn cmb = new DataGridViewComboBoxColumn();
cmb.HeaderText = "cat";
cmb.Name = "cmb";
cmb.DataSource=ds2
Can you point out whats wrong in my code, or help me in another way to solve my problem
Upvotes: 0
Views: 488
Reputation: 1583
You need to format each column using a DataGridViewTextBoxColumn or DataGridViewComboBoxColumn and add it to the DataGridView. Be sure to set AutoGenerateColumns to false. Something like:
dataGridView1.Columns.Clear();
dataGridView1.AutoGenerateColumns = false;
DataGridViewTextBoxColumn column = new DataGridViewTextBoxColumn();
column.DataPropertyName = "Description";
column.Name = "Description";
column.HeaderText = "Description";
column.Width = 150;
//column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
dataGridView1.Columns.Add(column)
DataGridViewComboBoxColumn ccolumn = new DataGridViewComboBoxColumn();
ccolumn.DataPropertyName = "cmb";
ccolumn.Name = "cmb";
ccolumn.HeaderText = "Cat";
ccolumn.Width = 65;
ccolumn.DataSource = ds2;
ccolumn.DisplayMember = "cat";
ccolumn.ValueMember = "cat";
dataGridView1.Columns.Add(ccolumn);
Do all the columns like this before you assign the DataSource to the DataGridView.
Upvotes: 1