inserting data from datagridview to database

倖福魔咒の 提交于 2019-12-09 23:34:12

问题


There are some existing data in the database and users will be entering new data into the datagridview which I wanted to add into database.

And I really don't know how to add ONLY the new inserted rows of data in datagridview into the database. How do I get the new inserted data only? I was told that I can use tempID to assign it to the new inserted row, but I have no idea on how to do it. Can anyone give me some links to it?

This is my code for now:

private void button1_Click(object sender, EventArgs e)
{
    con = new System.Data.SqlClient.SqlConnection();
    con.ConnectionString = "Data Source=tcp:SHEN-PC,49172\\SQLEXPRESS;Initial Catalog=LSEStock;Integrated Security=True";
    con.Open();
    SqlDataAdapter da = new SqlDataAdapter();

    for (int i = 0; i<dataGridView1.Rows.Count-2; i++ )
    {

        String insertData = "INSERT INTO CostList(SupplierName, CostPrice, PartsID) VALUES (@SupplierName, @CostPrice, @PartsID)" ;
        SqlCommand cmd = new SqlCommand(insertData, con);
        cmd.Parameters.AddWithValue("@SupplierName", dataGridView1.Rows[i].Cells[0].Value);
        cmd.Parameters.AddWithValue("@CostPrice", dataGridView1.Rows[i].Cells[1].Value);
        cmd.Parameters.AddWithValue("@PartsID", textBox1.Text);
        da.InsertCommand = cmd;
        cmd.ExecuteNonQuery();
    }

    con.Close();
}

回答1:


I think you should approach the datagrid insert differently. check this out:

http://www.codeguru.com/csharp/.net/net_data/datagrid/article.php/c13041/Add-Edit-and-Delete-in-DataGridView.htm

I don't think allowing local work and then inserting all the new rows is the best approach here when the grid is able to let users insert new rows to the database when there is databound. the example does the database calls asynchronously to free the UI.

also I think you should at least use StringBuilder for your query; more manageable and I hope you are not really going to leave the connection string there like that.



来源:https://stackoverflow.com/questions/11927864/inserting-data-from-datagridview-to-database

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