0

我制作了一个DataGridViewTextBoxColumn名为“prod”的产品,其中列出了所有产品名称和 ID。

现在我正在尝试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();
    }
4

1 回答 1

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;
        }
于 2012-11-19T19:28:38.277 回答