DataGridview Combobox显示来自数据源

时间:2017-08-16 16:11:21

标签: c# winforms datagridview

FORM IMAGE

我的数据库中有两个表

  1. 数据表
  2. KAR
  3. datatable有两列Product,Producttype。 kar表也有两列类型,税。

    在我的表单中,我有一个Datagridview,包含3列Productname,type,tax。

    Productname列是datagridviewcomboboxcolumn,显示来自datatable的所有产品。 `

    public Form5()
        {
            InitializeComponent();
        }
    
        private void Form5_Load(object sender, EventArgs e)
        {
            this.datatableTableAdapter.Fill(this.myBillDataSet.datatable);
            dataGridView1.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView1_EditingControlShowing);
    
        }
    
        private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            ComboBox combo = e.Control as ComboBox;
            if (combo != null)
            {
                combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);
                combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);
            }
        }
        string item = null;
        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(@"Data Source=ZEE-PC\SQLEXPRESS;Initial Catalog=MyBill;Integrated Security=True");
    
            ComboBox cb = (ComboBox)sender;
            item = cb.Text;
            if (item != null)
            {
                SqlCommand cmd = new SqlCommand("select Producttype from datatable where product=@pro", con);
    
                cmd.Parameters.AddWithValue("@pro", item);
                con.Open();
                string val = cmd.ExecuteScalar().ToString();
                con.Close();
    
    
                SqlCommand cmd2 = new SqlCommand("select tax from kar where type=@pro2", con);
    
                cmd2.Parameters.AddWithValue("@pro2", val);
                con.Open();
                string val2 = cmd2.ExecuteScalar().ToString();
                con.Close();
            }
    
        }
    

    当用户从下拉列表中选择任何产品时,类型和税收列将显示该值。我正在获取值但无法在gridview单元格中显示

1 个答案:

答案 0 :(得分:0)

您可以使用列索引

直接在ComboBox_SelectedIndexChanged事件中的单元格中插入值

dataGridView1.Rows[e.RowIndex].Cells[YourCellindex] = val;
dataGridView1.Rows[e.RowIndex].Cells[YourSecondCellindex] = val2;

dataGridView1.BeginEdit(true);
dataGridView1.EndEdit();

希望有所帮助