当用户点击GridView中的“删除”按钮时,我的代码会删除数据库中的行,但GridView没有更新以反映新的数据更改。
这是我的代码:
<asp:GridView runat="server" ID="grdQuestions" AutoGenerateColumns="false" Width="100%" CellSpacing="10"
PagerSettings-Visible="true">
<HeaderStyle CssClass="aspNetHeader" />
<Columns>
<asp:BoundField DataField="QuestionID" HeaderText="QID" />
<asp:BoundField DataField="ModuleID" HeaderText="Mod #" />
<asp:BoundField DataField="QuestionText" HeaderText="Question" />
<asp:BoundField DataField="CorrectAnswer" HeaderText="Answer" />
<asp:BoundField DataField="AnswerNote" HeaderText="Note" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="lnkEdit" Text="Edit"></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDelete" Text="Delete" CommandArgument='<%# eval("QuestionID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Protected Sub grdQuestions_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles grdQuestions.RowCommand
If e.CommandName = "Delete" Then
sql = "delete from tmp_Questions where QuestionID = " & e.CommandArgument
Dim cmd As New SqlCommand(sql, d.SQLConnection)
d.SQLConnection.Open()
cmd.ExecuteNonQuery()
d.SQLConnection.Close()
GetModuleData()
End If
End Sub
Protected Sub grdQuestions_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles grdQuestions.RowDeleting
GetModuleData()
End Sub
Private Sub GetModuleData()
' ddlModules is a drop down where the user can select a module to filter questions by.
Dim selid As Integer = ddlModules.SelectedItem.Value
sql = "select QuestionID, ModuleID, LEFT(QuestionText, charindex(' ', QuestionText, 30)) as QuestionText, CorrectAnswer," & vbCrLf & _
"AnswerNote from tmp_Questions" & vbCrLf & _
"where ModuleID = " & selid & vbCrLf & _
"order by ModuleID"
Dim cmd As New SqlCommand(sql, d.SQLConnection)
cmd.CommandText = sql
QuestionAdapter.SelectCommand = cmd
QuestionAdapter.Fill(QuestionData)
If QuestionData.Tables(0).Rows.Count > 0 Then
grdQuestions.DataSource = QuestionData
grdQuestions.DataBind()
End If
End Sub
提前感谢您的光临!
编辑1:
是否有人踩过代码,发现e.CommandArgument
没有获得grdQuestions_RowCommand
编辑1(修订):
e.CommandArgument
没有得到价值的事实是我的错。我改变了它的值的分配方式,而没有删除以前的方法。
代码将运行grdQuestions_RowCommand
,然后进入grdQuestions_RowDeleting
,然后执行GetModuleData
我有一种感觉,要查看对网格的更改,可能需要PostBack,但我已将所有DataBinding删除到If Not IsPostBack Then
块,因为替代方法导致DropDownList出现问题,其选择用作填充的引用网格(ddlModules选择了其问题将显示在网格中的模块)。
答案 0 :(得分:0)
您既没有为CommandName="Edit"
指定lnkEdit
,也没有为CommandName="Delete"
指定lnkDelete
。
我觉得要查看对网格的更改,可能需要PostBack
当然,必须发生回发,并且在删除记录后,GridView必须再次数据绑定到它的DataSource。但是,当用户单击删除链接并且grdQuestions_RowDeleting
已被处理时,已经发生了该回发。
调试并确保记录被删除,之后 GridView再次获得数据绑定。