Save changes from dataGridView to SQL Server DB

只谈情不闲聊 提交于 2020-01-25 02:09:32

问题


I have a form with dataGridView to display content of table Attendance

    TagID      SessionID       ScanningTime
    ---------------------------------------
    4820427      Test1       14/08/2013 18:12

I would like to add a record manually to the table to look like this....

    TagID      SessionID       ScanningTime
    ---------------------------------------
    4820000      Test1       14/08/2013 18:12
    0000001      Test2       15/08/2012 17:00

...and save changes to SQL Server database after button has been clicked.

I have tried creating UPDATE query:

command.Text = "UPDATE Attendance
SET TagID= @tagNo, SessionID= @sessionNo, ScanningTime= @scantime"; 

But I'm not sure how to assign values from DGV to parameters.

What is the correct way to save changes from dataGridView to SQL Server database?

Please note that I do not use DataSet or TableAdapter when working with DGV.


回答1:


You're going to want to consume the RowsAdded method of the DataGridView and cache the necessary information to INSERT the data:

// new form field for caching
private List<DataGridViewRow> _addedRowsCache = new List<DataGridViewRow>();

private void dataGridView1_RowsAdded(object sender,
    DataGridViewRowsAddedEventArgs e)
{
    for (int i = e.RowIndex; i < e.RowIndex + e.RowCount; i++)
    {
        _addedRowsCache.Add(dataGridView.Rows[i]);
    }
}

and then when you're ready to submit the data to the database:

// new class field to store the INSERT sql
private string _insertSQL = "INSERT INTO tbl (field1, field2) VALUES (@field1, @field2)";

// this block goes inside the click event
if (_addedRowsCache.Count > 0)
{
    using (SqlConnection c = new SqlConnection(connString))
    {
        c.Open();

        foreach (DataGridViewRow r in _addedRowsCache)
        {
            using (SqlCommand cmd = new SqlCommand(sql, c))
            {
                // add any parameter values, I don't know where `val(n)`
                // comes from here. Maybe from the `DataBoundItem`
                // off the `DataGridViewRow`, or maybe from a `Cell`
                // out of the `Cells` collection of the `DataGridViewRow`
                cmd.Parameters.AddWithValue("@field1", val1);
                cmd.Parameters.AddWithValue("@field2", val2);

                cmd.ExecuteNonQuery();
            }
        }
    }
}


来源:https://stackoverflow.com/questions/18256744/save-changes-from-datagridview-to-sql-server-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!