简体   繁体   中英

Single datagridview row updating

Could you help with such problem: I have two forms, datagridview and SQL database. On Load event of my first form I'm select some data from my SQL database by using stored procedure(select query).

SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("PROC001", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
datagridview.DataSource = dt;

After that, I can filter or sort my datagridview by using dt.DefaultView.Filter = .... and display in my grid only filtered rows. On CellMouseDoubleClick event my second Form2 appearing. In this form I update some value in database by clicking on Button1 and also after that I want to update my selected datagridview row. My quetions are:

1) How can I update only selected row in datagridview and do not execute stored procedure for all datagridview filling again.

2) My datagridview is already filtered, so if I execute procedure again, my filter has been disapeared. How can I avoid of this?

3) On Form2 I'm updating some database value, that is not included in my "select query" as selected field, but this value is affected on this query. Example:

SELECT Name, SecondName FROM tUsers 
  WHERE id = (SELECT DISTINCT id FROM tProcedures WHERE Code = 'First')

In my datagridview I can see Name and SecondName, but in Form2 I'm updating Code in tProcedures database table. So after updating I want to see my new data in datagridview, only in selected row and with current filter. I don't want to SELECT all data again to datagridview and broke my filter.

Is it possible to update single row? Could you provide some examples?

Because the DataGridView is using DataBinding, you have to update the underlying data source, in this case the DataTable. See How to: Edit Rows in a DataTable for how to do that.

For the filter issue, you would want to save and restore the filter:

var filter = dt.DefaultView.RowFilter;
UpdateData();
dt.DefaultView.RowFilter = filter;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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