Connecting Tech Pros Worldwide Help | Site Map

DataGridView - loop through selected rows, change value of sorted coloumn.

Newbie
 
Join Date: Mar 2008
Posts: 29
#1: 4 Weeks Ago
Hi Everyone,

So I have a datagridview and it has a column called status. It has 3 values: New, Printed, and Shipped.

Now a user can select multiple rows and click "set to printed". I then do a foreach loop on datagridview.selectedrows and change the status to printed. Now the problem is that if the datagridview is sorted by status, when the status is changed from new to printed, that row is moved from being under new to printed and all the code after is executed on the next row. Here is what the code looks like.

Expand|Select|Wrap|Line Numbers
  1.  For Each row As System.Windows.Forms.DataGridViewRow In frmMain.OrderDataGridView.selectedRows
  2.             row.Cells("status").Value = "Printed"
  3.             row.Cells("test").Value = "test"
  4.         Next
  5.  
So, like I said before, if the datagridview is sorted by the status cloumn, and 2 rows are selected. Then first row will hit the first line of code, execute it and change postion. So the 2nd row becomes the 1st row and row("status") is not changed. Any ideas on how to resolve this?
tlhintoq's Avatar
Moderator
 
Join Date: Mar 2008
Location: Arizona, USA
Posts: 1,743
#2: 4 Weeks Ago

re: DataGridView - loop through selected rows, change value of sorted coloumn.


A.
Copy the data out of the grid so you don't have to fight the auto sort.
Do your calculations.
Put the data back into the grid.

B.
Don't do a Foreach loop.
Use a conventional 'for' loop with an int you can use for the index. That way when item 27 becomes item 9 you don't care; you still move on to item 28.
Newbie
 
Join Date: Mar 2008
Posts: 29
#3: 4 Weeks Ago

re: DataGridView - loop through selected rows, change value of sorted coloumn.


What I ended up doing was saving the dgv to the database, did a sql query on to update the status in the database, then refreshed the datagridview. Thanks for your help man!
Reply