单击按钮如何在数据网格视图中更新多行数据

时间:2018-06-25 17:17:51

标签: c# .net winforms datagridview

这是我的按钮点击操作。单击此按钮后,只有在网格视图中已编辑的行必须更新。就我而言,网格中所有行都在更新传入的数据。它必须是多次数据更新

private void button1_Click(object sender,EventArgs e )
{
    dataGridView1.CellEndEdit += DataGridView1_CellValueChanged;
}
private void DataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // Update the balance column whenever the value of any cell changes.
  int s= e.RowIndex;
  SqlConnection connection = new SqlConnection(@"Data Source= 
     (LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\udevarasetti      
     \Desktop\New folder (2)\RPAPoC\RPAPoC\RPA_DB.mdf;Integrated
     Security=True;Connect     Timeout=30");
    // Console.WriteLine(a);
    for (int i = 0; i < a; i++)
    {
        var quantity = dataGridView1.Rows[i].Cells["ApprovedQTY"].Value.ToString();
        var ItemNumber = dataGridView1.Rows[i].Cells["ItemNumber"].Value.ToString();
        try
        {
            SqlCommand sc = new SqlCommand($"UPDATE Transaction_Table
            SET 
            Approved_QTY = '{quantity}',
            Approved_Date = '{DateTime.Now.ToString("yyyy-MM-dd")}' 
            WHERE PO_NBR= '{comboBox1.SelectedItem.ToString()}' 
            and Item_No='{ItemNumber}'", connection);

            connection.Open();
            int a = sc.ExecuteNonQuery();
            con.Close();

            cmd = new SqlCommand("select  i.Item_No AS 'Item Number', i.Item_Description AS 'Item Name', t.Item_QTY AS Quantity, i.Item_Price AS Price, t.Approved_QTY 
            AS 'Approved QTY', t.Approved_Date AS 'Approved Date' from PurchaseOrder p 
            join Transaction_Table t on p.PO_NBR = t.PO_NBR join Item i on 
            t.Item_No=i.Item_No where p.PO_NBR ='" + comboBox1.Text + "'", con);

            con.Open();
            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            dataGridView1.DataSource = dt;
            con.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
    MessageBox.Show("Success");
}

0 个答案:

没有答案