0

DataGridViewTextBoxColumnすべての製品名と ID をリストする「prod」という名前を作成しました。

今、私は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 に答える