سؤال

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();
}
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top