2012-11-19 26 views
0

我制作了DataGridViewTextBoxColumn,名为“prod”,其中列出了所有产品名称和id。使用datagridviewcomboboxcolumn的值将datagridviewtextboxcolumn绑定到数据库

现在我试图让DataGridViewTextBoxColumn其得到DataGridViewTextBoxColumn所选产品的价格。

private void Form1_Load(object sender, EventArgs e) 
{ 
    SqlConnection con = new SqlConnection(constring); 
    SqlCommand cmd = new SqlCommand("select First_Name,Customer_id from customers",con); 
    SqlDataAdapter Adapter = new SqlDataAdapter(cmd); 
    DataSet ds = new DataSet(); 
    Adapter.Fill(ds,"customers"); 
    comboBox1.DataSource = ds.Tables["customers"]; 
    comboBox1.DisplayMember = "First_Name"; 
    comboBox1.ValueMember = "Customer_id"; 

    SqlConnection cons = new SqlConnection(constring); 
    SqlCommand cmds = new SqlCommand("select product_id,Product_Name from Products", cons); 
    SqlDataAdapter Adapters = new SqlDataAdapter(cmds); 
    DataSet dss = new DataSet(); 
    Adapters.Fill(dss, "Products"); 

    //DataGridViewComboBoxColumn prod = new DataGridViewComboBoxColumn(); 

    prod.DataSource = dss.Tables["Products"]; 
    prod.DisplayMember = "Product_Name"; 
    prod.ValueMember = "product_id"; 
    dataGridView1.Columns.Add(prod); 
    price_txt = new DataGridViewTextBoxColumn(); 
    price_txt.HeaderText = "price"; 
    price_txt.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; 
    dataGridView1.Columns.Add(price_txt); 
} 

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) 
{ 
    //SqlConnection cons = new SqlConnection(constring); 
    //string cmdstring = string.Format("select Price from products where product_id='{0}'",id); 
    //SqlCommand cmd = new SqlCommand(cmdstring,cons); 
    //con.Open(); 
    SqlConnection cons = new SqlConnection(constring); 
    if (e.ColumnIndex ==0) 
    { 
     //SqlConnection cons = new SqlConnection(constring); 
     int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString()); 
     string cmdstring = "select Price from Products where product_id= "+id; 
     SqlCommand cmd = new SqlCommand(cmdstring, cons); 
     cons.Open(); 
     int p = Convert.ToInt32(cmd.ExecuteScalar()); 
     dataGridView1.Rows[e.RowIndex].Cells[1].Value = p; 
     cons.Close(); 
    } 

回答

0

您可以添加CellValueChanged事件处理程序为您DataGridView控制,然后做这样的事情:

private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
     { 
      if(dataGridView1.Columns[ e.ColumnIndex] is DataGridViewComboBoxColumn) 
        dataGridView1.Rows[e.RowIndex].Cells[iTextBoxColumn].Value = ((DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex]).ValueMember; 
     } 
+0

我觉得这段代码将使datagridviewtextboxcolumn的价值= datagridviewcombobox的价值,但我想获取价格的comboboxcolumn的id值 –

+0

现在查看答案! –

+0

它doesnot工作 –

相关问题