简体   繁体   English

将数据从datagridview插入数据库

[英]inserting data from datagridview to database

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. 数据库中已有一些现有数据,用户将向我想添加到数据库的datagridview中输入新数据。

And I really don't know how to add ONLY the new inserted rows of data in datagridview into the database. 而且我真的不知道如何仅将datagridview中新插入的数据行添加到数据库中。 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. 有人告诉我可以使用tempID将其分配给新插入的行,但是我不知道该如何做。 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();
}

I think you should approach the datagrid insert differently. 我认为您应该以不同的方式处理datagrid插入。 check this out: 看一下这个:

http://www.codeguru.com/csharp/.net/net_data/datagrid/article.php/c13041/Add-Edit-and-Delete-in-DataGridView.htm 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. 该示例执行数据库异步调用以释放UI。

also I think you should at least use StringBuilder for your query; 我也认为您至少应使用StringBuilder进行查询; more manageable and I hope you are not really going to leave the connection string there like that. 更易于管理,我希望您不会真的将连接字符串留在那里。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM