我不认为这有一个重复的问题......但是在这里。我想删除datagridview中的选定行。在按住ctrl并单击鼠标的同时,我将在datagridview中选择多行。问题是,当我单击删除按钮时,将删除唯一的第一个选定行。
这是我的代码:
Private Sub deleteitem()
Dim result As DialogResult
result = MessageBox.Show("Are you sure you want to delete selected item/s?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
Dim row As DataGridViewRow = DataGridView2.CurrentRow
cmd.Connection = con
Dim query As String = "update Items_tbl set itemstatus='UNAVAILABLE' where id=@id"
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@id", row.Cells(0).Value.ToString())
con.Open()
For Each Parameter As SqlParameter In cmd.Parameters
If Parameter.Value Is Nothing Then
Parameter.Value = DBNull.Value
End If
Next
cmd.ExecuteNonQuery()
End Using
MessageBox.Show("Item/s deleted.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
con.Close()
txt_ItemName.Clear()
txt_CostPrice.Clear()
txt_MarkupPrice.Clear()
txt_Price.Clear()
txt_ItemName.Focus()
form_AdminMainPage.Uc_FileMaintenance_Admin1.loaditems()
resetitems()
End If
答案 0 :(得分:1)
尝试以下代码:
Dim result As DialogResult
result = MessageBox.Show("Are you sure you want to delete selected item/s?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If result = DialogResult.Yes Then
cmd.Connection = con
For Each row As DataGridViewRow in DataGridView2.SelectedRows
Dim query As String = "update Items_tbl set itemstatus='UNAVAILABLE' where id=@id"
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("@id", row.Cells(0).Value.ToString())
con.Open()
For Each Parameter As SqlParameter In cmd.Parameters
If Parameter.Value Is Nothing Then
Parameter.Value = DBNull.Value
End If
Next
cmd.ExecuteNonQuery()
End Using
Next
MessageBox.Show("Item/s deleted.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
con.Close()
txt_ItemName.Clear()
txt_CostPrice.Clear()
txt_MarkupPrice.Clear()
txt_Price.Clear()
txt_ItemName.Focus()
form_AdminMainPage.Uc_FileMaintenance_Admin1.loaditems()
resetitems()
End If
答案 1 :(得分:0)
您需要遍历行,并执行查询,更改每行的参数。这假设您已经打开了连接,因此它只是代码的命令部分。
Using cmd As New SqlCommand(query, con)
con.Open()
Dim param As New SqlParameter()
param.ParameterName = "@id"
cmd.Parameters.Add(param)
For Each r As DataGridViewRow in DataGridView2.SelectedRows
param.Value = r.Cells(0).Value.ToString()
cmd.ExecuteNonQuery()
Next
End Using