【发布时间】:2013-06-07 17:53:21
【问题描述】:
再次。
在 gridview 标记上,我有这些:
<asp:TemplateField HeaderText="Dates">
<ItemTemplate>
<asp:Label ID="dates_label runat="server" Text='<%# Bind("shipDates","{0:M/dd/yyyy}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="ehide" Value='<%# Eval("eventId") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
gridview 显示几行记录并使用隐藏的表单字段,我可以将一行与事件表中的特定 eventid 关联起来。
下面是尝试删除每一行记录的代码隐藏。
For Each row As GridViewRow In GridView1.Rows
Dim dates_label = DirectCast(row.FindControl("dates_label"), Label)
Dim shipDates = Date.ParseExact(dates_label.Value, "M/dd/yyyy", Nothing)
Dim ehide = DirectCast(row.FindControl("ehide"), HiddenField)
Dim eventid = ehide.Value
Dim myConnectionString As [String] = ConfigurationManager.ConnectionStrings("DBConnectionString").ConnectionString
Dim myConnection As New SqlConnection(myConnectionString)
Try
myConnection.Open()
strSQL = "Delete from tblEvents where username=@UserName and eventid = @eventid"
com = New SqlCommand(strSQL, myConnection)
com.Parameters.AddWithValue("@username", Session("username"))
com.Parameters.AddWithValue("@eventid", eventid)
Response.Write(strSQL)
Response.End()
com.ExecuteNonQuery()
myConnection.Close()
Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('Information Saved successfully')</SCRIPT>")
Response.Redirect("~/default.aspx")
Catch ex As SqlException
Response.Write("<SCRIPT LANGUAGE='JavaScript'>alert('" + ex.Message + "')</SCRIPT>")
Finally
myConnection.Close()
End Try
Next
当我在这个 sub 上运行调试器时,它会尝试删除具有第一个 eventid 的任何行。
例如,假设事件表中有 5 行记录,事件 ID 为 1、2、3、4、5。为简洁起见,这些是由数字组成的。
如果我尝试删除 eventId 为 1 的第一条记录,我会得到:
从 eventId = 1 的 tblEvents 中删除
如果我尝试删除 eventId 为 5 的行,我仍然会得到:
从 eventId = 1 的 tblEvents 中删除
如何解决此问题,以使每一行都被其 rowId 删除?
提前致谢。
【问题讨论】:
-
你能不能把
ehide的代码贴在asp:TemplateField里面,去掉asp.net-mvc标签,因为问题不是mvc。 -
@win,很抱歉 mvc 是一个错误。我想选择asp.net。感谢您纠正它。另外,非常抱歉,我发布了错误的代码。我现在已经发布了正确的代码。顺便说一句:如果有帮助,eventid 是整数。谢谢
-
为什么要重定向到循环中间的页面?
-
also -
eventid是主键,因此通常存储在 GridView DataKeyNames 集合中。将其添加为模板HiddenField是不好的。 -
@Kenny 你能确定从数据库中检索到的所有数据都有不同的
eventId吗?换句话说,eventId并不是所有行都为 1。