C# 单击按钮更改DataGridView单元格的值

C# 单击按钮更改DataGridView单元格的值,c#,winforms,datagridview,C#,Winforms,Datagridview,我只是想问一下,当我选择某一行时,如何更新或更改DataGridView中“quantity”列的单元格值。 我的DataGridView中有3列,分别是项目名称、数量和价格。 每次单击表单上的“添加”或“减少”按钮时,所选行项目的数量将在数量列中添加或减去1,并且价格也将在每次数量增加或减少时更新。这是我将项目添加到DataGridView时的代码 我不确定我是否正确地将项目添加到我的datagrid中 cmd = new MySqlCommand("SELECT * FROM tblmenu

我只是想问一下,当我选择某一行时,如何更新或更改DataGridView中“quantity”列的单元格值。 我的DataGridView中有3列,分别是
项目名称
数量
价格
。 每次单击表单上的“添加”或“减少”按钮时,所选行项目的数量将在数量列中添加或减去1,并且价格也将在每次数量增加或减少时更新。这是我将项目添加到DataGridView时的代码

我不确定我是否正确地将项目添加到我的datagrid中

cmd = new MySqlCommand("SELECT * FROM tblmenu", dbConn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
    Button btn = new Button();
    btn.Text = rdr["menuName"].ToString();
    btn.Width = 126;
    btn.Height = 80;
    btn.Click += delegate
    {
        MySqlConnection cnn2 = new MySqlConnection(sqlConn.connString);
        cnn2.Open();
        cmd = new MySqlCommand("SELECT menuName, menuPrice FROM tblmenu WHERE menuName = @name", cnn2);
        cmd.Parameters.AddWithValue("@name", btn.Text);
        MySqlDataReader rdr2 = cmd.ExecuteReader();
        while (rdr2.Read())
        {
            dataGridView1.Rows.Add(rdr2.GetString("menuName").ToUpper(), 1, rdr2.GetDouble("menuPrice"));
        }
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        lblQty.Text = dataGridView1.RowCount.ToString();
    };
}
我尝试过这个方法,但当我单击另一组项目时,上一个选定项目的数量仍然会增加

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    Add.Click += delegate
    {
        dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value) + 1;
    };
    Minus.Click += delegate
    {
        dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["quantity"].Value) - 1;
    };
}

首先,使用dataGridView1_CellContentClick根本不起作用。您打算在单击“添加”或“减号”按钮时增加或减少数量。我将使用dataGridView1.CurrentRow属性获取CurrentRow并操作quantity列。要更新price列,您应该使用Rate列或常量Rate值将其与quantity相乘。有吗?如果没有,我看不出你是如何计算价格的。但是,假设您有一个:

void quantity_change(object sender, EventArgs e){
    var row=dataGridView1.CurrentRow;

    if(row==null || row.Index<0) 
    return;
    var unit = (sender==add)?1:-1;
    var quantity = Convert.ToInt32(row.Cells["quantity"].Value) + unit;

    row.Cells["quantity"].Value = quantity;
    //assuming you have rate column...
    var rate = Convert.ToDouble(row.Cells["Rate"].Value);
   row.Cells["Price"].Value = quantity * rate;
}

您也可以使用窗体的加载事件。

我建议您考虑将DATAGIDVIEW绑定到数据源。如果可以避免,则不应在UI上执行数据操作

为了证明这一点

private void quantityChangeClick(object sender, EventArgs e)
{
    addToQuantity((Button)sender == this.Add ? 1 : -1);
    updateTotal();
}

private void addToQuantity(int howMuch)
{
    var selectedRowIndices = dataGridView1.SelectedRows.OfType<DataGridViewRow>().Select(ro => ro.Index);
    this.rows.Where((r, i) => selectedRowIndices.Contains(i)).ToList().ForEach(
        r => r.Quantity = Math.Max(0, r.Quantity + howMuch));

    this.dataGridView1.Refresh();
}

// calculate the total from the data source as well
private void updateTotal()
{
    var total = Math.Round(this.rows.Sum(r => r.Quantity * r.Price), 2, MidpointRounding.AwayFromZero);
    this.TotalLabel.Text = string.Format("₱{0:0.00}", total);
}
private void quantityChangeClick(对象发送方,事件参数e)
{
addToQuantity((按钮)发送方==此。添加?1:-1);
updateTotal();
}
私有void addToQuantity(整数多少)
{
var selectedRowIndexes=dataGridView1.SelectedRows.OfType().Select(ro=>ro.Index);
this.rows.Where((r,i)=>SelectedRowIndexs.Contains(i)).ToList().ForEach(
r=>r.数量=数学最大值(0,r.数量+多少);
this.dataGridView1.Refresh();
}
//也可以从数据源计算总数
私有void updateTotal()
{
var total=Math.Round(this.rows.Sum(r=>r.Quantity*r.Price),2,中点舍入(middpointrounding.AwayFromZero);
this.totalabel.Text=string.Format(“{0:0.00}”,总计);
}
我已经使用了一些虚拟数据来演示这一点,即Row类。实际上,您可以做类似的事情,使用数据库中的每条记录向数据源行添加一行

private class Row
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
    public Row(string i, int q, double p)
    {
        this.ItemName = i;
        this.Quantity = q;
        this.Price = p;
    }
}

private List<Row> rows = new List<Row>();

private void Form1_Load(object sender, EventArgs e)
{
    // instead, here you will add your rows from SQL
    rows.AddRange(new Row[]
    {
        new Row("item1", 0, 500),
        new Row("item2", 0, 400),
        new Row("item3", 0, 850)
    });
    this.dataGridView1.DataSource = rows;
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    Add.Click += quantityChangeClick;
    Minus.Click += quantityChangeClick;
}
私有类行
{
公共字符串ItemName{get;set;}
公共整数数量{get;set;}
公共双价{get;set;}
公共行(字符串i、整数q、双p)
{
this.ItemName=i;
这个。数量=q;
这个价格=p;
}
}
私有列表行=新列表();
私有void Form1\u加载(对象发送方、事件参数e)
{
//相反,这里您将从SQL添加行
rows.AddRange(新行[])
{
新行(“项目1”,0,500),
新行(“项目2”,0,400),
新行(“项目3”,0,850)
});
this.dataGridView1.DataSource=行;
dataGridView1.SelectionMode=DataGridViewSelectionMode.FullRowSelect;
添加。单击+=数量更改单击;
减。单击+=数量更改单击;
}

哇。这是可行的:)我现在的问题是如何在每次单击加减按钮时动态地乘以数量列或价格。我已经根据您的价格更新要求改进了我的答案。如果我的答案能解决你的问题,请注明我的答案已被接受。还请仔细阅读@Verdolino'的答案建议。这是一个正确的做法,也是一个很好的答案。“懒汉海盗”我很高兴我的回答解决了你的问题。
private class Row
{
    public string ItemName { get; set; }
    public int Quantity { get; set; }
    public double Price { get; set; }
    public Row(string i, int q, double p)
    {
        this.ItemName = i;
        this.Quantity = q;
        this.Price = p;
    }
}

private List<Row> rows = new List<Row>();

private void Form1_Load(object sender, EventArgs e)
{
    // instead, here you will add your rows from SQL
    rows.AddRange(new Row[]
    {
        new Row("item1", 0, 500),
        new Row("item2", 0, 400),
        new Row("item3", 0, 850)
    });
    this.dataGridView1.DataSource = rows;
    dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    Add.Click += quantityChangeClick;
    Minus.Click += quantityChangeClick;
}