Click here to Skip to main content
15,919,341 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hye, I use this code to convert gridview dataset into new datable.
Then when certain row for DEPT cell meets same condition as variable prodName,it will delete the datarow.
If dtDeleteSh contains only 1 row, this codes work. However datatable with more than 1 datarow will display an error "There is no row at position 1/2/3"

SQL
Dim dtDeleteSh As New DataTable
                         dtDeleteSh.Columns.Add("check")
                         dtDeleteSh.Columns.Add("DEPT")
                         dtDeleteSh.Columns.Add("NAME_T")
                         dtDeleteSh.Columns.Add("EMPID_T")



For shRow As Integer = 0 To gdShop.Rows.Count - 1

      Dim rowdeleteSh As DataRow = dtDeleteSh.NewRow()
      rowdeleteSh = dtDeleteSh.NewRow
      rowdeleteSh("check") = gdShop.Rows(shRow).Cells(0).Text
      rowdeleteSh("DEPT") = gdShop.Rows(shRow).Cells(1).Text
      rowdeleteSh("EMPID_T") = gdShop.Rows(shRow).Cells(2).Text
      rowdeleteSh("NAME_T") = gdShop.Rows(shRow).Cells(3).Text

      dtDeleteSh.Rows.Add(rowdeleteSh)

Next


For countSh As Integer = 0 To dtDeleteSh.Rows.Count - 1


     If prodName = dtDeleteSh.Rows(countSh)("DEPT").ToString Then
             dtDeleteSh.Rows(countSh).Delete()

     End If
Next


     gdShop.DataSource = dtDeleteSh
     gdShop.DataBind()


The error occurs here

If prodName = dtDeleteSh.Rows(countSh)("DEPT").ToString Then
Posted
Comments
dimpledevani 29-Aug-12 0:46am    
when you are deleting a row the total number of rows in your datatable also changes so the error is valid as you are in a loop.Try to make a copy of your datatable and in for loop for assigning the max value use one table and delete rows in other table

1 solution

try this c#, plz convert to VB.net, I did some conversion hints try:
C#
dtDeleteSh =   dtDeleteSh.AsEnumerable().Where(a => a["DEPT"].ToString()!=prodName ).CopyToDataTable();



Sample vb:(dont know it's correct syntax)
VB
dtDeleteSh = (From del In dtDeleteSh _
Where del!DEPT.ToString <> prodName _
Select del).CopyToDataTable()


the logic is select rows that are to keep and avoid the one's to delete and reassign this to existing datatable.
 
Share this answer
 
v4
Comments
snamyna 29-Aug-12 0:45am    
By using remove row, The next function would not execute because the datatable is modified. Am I right?
Kuthuparakkal 29-Aug-12 1:56am    
updated soln, plz check.. thats Linq method.
snamyna 31-Aug-12 3:08am    
Thanks. :)
Kuthuparakkal 31-Aug-12 9:11am    
You're welcome... did it help you ? if so mark answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900