0

再次。

在 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 删除?

提前致谢。

4

1 回答 1

0

基于我们讨论的假设。

  1. 您有一个启用了行选择的 gridview
  2. 您还启用了删除行。(EDIT: Just rememberd this option won't be available until you place the delete command in the SqlDataSource control)
  3. 该 eventid 来自数据库

如果这一切都是真的,那么删除行非常容易:

  1. 通过属性页将 eventid 放置在 GridView1 DataKeyNames 中。
  2. 从设计器中选择连接到 GridView1 的 SqlDataSource 控件
  3. 在 SqlDataSource 属性列表中

    • 一个。找到 DeleteQuery 并选择它的 (Query)
    • 湾。这将打开命令和参数编辑器对话框
      1. 删除命令:"DELETE FROM tblEvents WHERE (username = @UserName) AND (eventid = @eventid)
      2. 单击Refresh Parameters对话框中的按钮
      3. 用户名:参数Source为Session,SessionField视情况而定
      4. eventid:参数Source为Control,ControlID为GridView1
  4. 全部保存

现在删除命令已“连接”到您的主键(eventid)并且删除应该可以正常工作

于 2013-06-07T19:39:55.187 回答