我使用v s 2010 我有一个问题..当我使用datagridview的复选框从后端数据库删除多一行...当我删除连续多一行时,它在后端保持我的字段NO .... ...
但是假设当我删除第2行和第4行然后.......它无法维持后端..... 我的编程是* 当我删除一行然后所有的那一行得到的时候没有字段编号就像n = n-1 *
我的代码在这里......任何人都可以解决它......
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
答案 0 :(得分: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))
然而,更长的答案是我认为你的代码可能比它需要的更麻烦,并且需要更多的DB调用。一个示例是,当您可能应该使用While
或For
时,可以使用For Each
。
以下是建议的重构(但请注意,我不明白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