0

I have 2 columns which are Name and Price. Assume that there are already some data in the database table which will be shown in the datagridview. Now, when users entered the new rows of data(no matter how many rows), and they click on the Save button, all the new rows of data will be save into the database.

The question is, how do I catch only the new rows of data? OR how do I check if the name exist, check if the price same, then do not insert, if different price, then update the price.

Here is my code:

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; 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();

EDIT : the above code will add every data in the datagridview into database and keep on duplicating.

Thanks for your attention.

2 Answers 2

1

One way is to delete all the data in the sql table and then insert what ever the data you have in the grid view.

Another way to get around this problem is create a column with name tempid in the grid view and assign value -1 for all the new rows being inserted and on save click get the rows only with tempid=-1 and insert them into the sql table.

Sign up to request clarification or add additional context in comments.

2 Comments

can u provide some sample codes for me to refer? or some links, thanks
0

load your data to dataset and datatable in it. and one other datatable (main data) object.

after insert rows in datagrid and save clicked, check your new data with main data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.