将组合框添加到数据网格视图

时间:2016-04-13 20:31:41

标签: c#

我正在尝试将一个组合框添加到数据网格视图中。这是datagrid视图的代码

           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";

对于datagrid视图中的第5列我正在尝试将其设置为组合框并从我的数据库中的类别表中读取类别名称。

我从这段代码开始,但我不知道如何完成它

        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

你能指出我的代码中有什么问题,或以其他方式帮助我解决我的问题

1 个答案:

答案 0 :(得分:1)

您需要使用DataGridViewTextBoxColumn或DataGridViewComboBoxColumn格式化每个列,并将其添加到DataGridView。务必将AutoGenerateColumns设置为false。类似的东西:

    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);

在将DataSource分配给DataGridView之前,请执行所有这样的列。