2010-12-17 84 views
0

我用vs 2010 我有一個問題..當我從後端數據庫使用datagridview的複選框刪除多個行....當我刪除連續多於一行保持一個我的領域NO在後端.......問題刪除多行,然後使用datagridview複選框

但假設當我刪除行2和4然後.......它不能保持後端..... 我的節目是* 當我刪除一行,那麼所有然後getherthan該行的■無場數是像N = N-1 *

我的代碼是h ERE ....任何一個可以解決這個問題.....

Dim i, j, n As Integer 
i = 0 
j = 0 
Dim x As Integer = 0 
Dim a(1000) As String 
a(x) = "" 
Try 
    While i < DataGridView1.Rows.Count 
     If DataGridView1.Rows(i).Cells(0).Value() Then 
       n = DataGridView1.Rows(i).Cells(1).Value() 
       Call openconnection() 
       'Here It Will Delete your Row From The Database Depending On Your Id.... 
       str = "DELETE FROM Assets_Detail Where No=" & n & "" 
       cmd = New SqlCommand(str, cn) 
       cmd.ExecuteNonQuery() 
       a(x) = n.ToString 

       cn.Close() 
       x = x + 1 



     End If 
     i = i + 1 
    End While 
Catch ex As Exception 
    MsgBox(ex.ToString()) 
End Try 
While j <= Val(a(x)) 
    Dim temp As Integer 
    temp = Val(a(x)) 
    Call openconnection() 
    str = "update Assets_Detail set No=No-1 where No > " & temp & "" 
    cmd = New SqlCommand(str, cn) 
    cmd.ExecuteNonQuery() 
    cn.Close() 

    j = j + 1 
End While 

回答

1

簡短的回答是,我認爲你正在使用x當你想用j和/或使用一個值,而不是長度的陣列。換句話說,下面的代碼:

While j <= Val(a(x)) 
    Dim temp As Integer 
    temp = Val(a(x)) 

應該可能是

While j <= a.Count() 
    Dim temp As Integer 
    temp = Val(a(j)) 

然而,較長的答案是,我認爲你的代碼可能是一個有點凌亂比它需要和更有數據庫調用超出需要。一個例子是,當您可能應該使用ForFor Each時,您使用While。 以下是建議重構(不過請注意,我不明白update Assets_Detail位如何工作的,所以至少這一點可能是完全錯誤的):

Dim ids As New List(Of Integer) 
    Try 
     For Each row As DataRow In DataGridView1.Rows 
      If row.Cells(0).Value() Then 
       n = row.Cells(1).Value()      
       ids.Add(CInt(n)) 
      End If 
     Next 

     Using cn As New SqlConnection("connectionstringhere") 
      cn.Open() 
      Dim Str As String = "DELETE FROM Assets_Detail Where No IN {0}" 
      Using cmd As New SqlCommand(String.Format(Str, String.Join(", ", ids.ToArray())), cn) 
       cmd.ExecuteNonQuery() 
      End Using 
     End Using 

    Catch ex As Exception 
     MsgBox(ex.ToString()) 
    End Try 
    Try 
     For Each id As Integer In ids 
      Using cn As New SqlConnection("connectionstringhere") 
       cn.Open() 
       Dim str As String = "update Assets_Detail set No=No-1 where No > {0} " 
       Using cmd As New SqlCommand(String.Format(str, id), cn) 
        cmd.ExecuteNonQuery() 
       End Using 
      End Using 
     Next 
    Catch ex As Exception 
     MsgBox(ex.ToString()) 
    End Try 
+0

我不能忍受在你的scond部分.....你能告訴我什麼是使用{0} – 2010-12-17 09:37:45

+0

@Gulu:這是因爲,而不是將字符串附加在一起我使用String.Format和{0}表示第二個參數String.Format應該插入那裏,如果有{1}第三個參數應該去那裏等等。請參閱這裏的更多細節:http://msdn.microsoft.com/en-us/library/system.string.format.aspx – 2010-12-17 09:40:41