【问题标题】:How can i delete selected data from grid on the button click event?如何在按钮单击事件上从网格中删除选定的数据?
【发布时间】:2011-05-19 05:46:49
【问题描述】:

我的页面上有一个网格,并使用复选框来检查网格中的一行或多行,我想通过单击网格外侧的删除按钮从网格中删除选中的行..

在表中我只有名称字段,没有像 ID 这样的字段。

如何删除记录。

提前谢谢..

这是我的代码我在做什么:-

private void GetData()
{

    ArrayList arr;
    if (ViewState["TotalRecords"] != null)
    {
        arr = (ArrayList)ViewState["TotalRecords"];
    }
    else
    {
        arr = new ArrayList();
    }
    for (int i = 0; i < grdlistWord.Rows.Count; i++)
    {

        CheckBox chk = (CheckBox)grdlistWord.Rows[i].Cells[1].FindControl("chkWord");
        if (chk.Checked)
        {
            if (!arr.Contains(grdlistWord.Rows[i].Cells[1]))
            {
                arr.Add(grdlistWord.Rows[i].Cells[1]);
            }
        }
        else
        {
            if (arr.Contains(grdlistWord.Rows[i].Cells[1]))
            {
                arr.Remove(grdlistWord.Rows[i].Cells[1]);
            }
        }

    }
    ViewState["TotalRecords"] = arr;
}

protected void lnkbtnDelete_Click(object sender, EventArgs e)
{

    try
    {
        int count = 0;

        ArrayList arr = (ArrayList)ViewState["TotalRecords"];
        count = arr.Count;
        for (int i = 0; i < grdlistWord.Rows.Count; i++)
        {
            if (arr.Contains(grdlistWord.Rows[i].Cells[1].Text))
            {
                Response.Write(grdlistWord.Rows[i].Cells[1].Text.ToString());
                DeleteRecord(grdlistWord.Rows[i].Cells[1].Text.ToString());
                arr.Remove(grdlistWord.Rows[i].Cells[1].Text);
            }
        }
        ViewState["TotalRecords"] = arr;
        GridBind();

    }
    catch (SqlException ex)
    {
        ex.ToString();
    }

}


private void DeleteRecord(string word)
{

    string query = "delete from searchword where word=@word";

    SqlCommand cmd = new SqlCommand(query, con);
    cmd.Parameters.AddWithValue("@word", word);
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
}

gridview html 细节:

 <fieldset>
        <legend>List</legend>
        <asp:GridView ID="grdlistWord" runat="server" DataKeyNames="word" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" OnRowDataBound="grdlistWord_RowDataBound" OnRowDeleting="grdlistWord_RowDeleting">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkWord" runat="server" onclick="check_click(this);" />

                    </ItemTemplate>
                    <HeaderTemplate>
                        <asp:CheckBox ID="chkAll" runat="server" onclick="checkAll(this);" />
                        <asp:LinkButton ID="ButtonDelete" runat="server" Text="Delete" OnClick="ButtonDelete_Click"></asp:LinkButton>
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="Word" HeaderText="Word" />
                <asp:HyperLinkField HeaderText="Edit" Text="edit" DataNavigateUrlFields="Word" DataNavigateUrlFormatString="SearchWord.aspx?words={0}&amp;mode=Edit" />
                <asp:CommandField ShowDeleteButton="True" HeaderText="Delete" />
            </Columns>
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <EditRowStyle BackColor="#999999" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <EmptyDataTemplate>Records not exist!</EmptyDataTemplate>
        </asp:GridView>

        <asp:HiddenField ID="hfCount" runat="server" Value = "0" />

    </fieldset>

【问题讨论】:

  • 您从这段代码中看到的行为是什么,您期待什么?您是否看到任何异常(除了代码无法编译)?
  • @p.campbell:它没有得到满足删除查询的 where 条件的单词。

标签: c# asp.net gridview


【解决方案1】:
 protected void lnkbtnDelete_Click(object sender, EventArgs e)
        {

            int counter = 0;
            List<string> words = new List<string>();
            foreach (GridViewRow rowitem in grdlistWord.Rows)
            {
                if (((CheckBox)rowitem.Cells[0].FindControl("chkWord")).Checked == true)//i consider that the check box is in the first column index ---> 0
                {
                    counter++;
                    words.Add(rowitem.Cells[1].Text); //i consider that the word is in the second column index ---> 1
                }
            }
            /////////////////////////////////////////////////////////////
            if(counter == 0) //no checks
            {

             //show some message box to clarify that no row has been selected.

            }
            /////////////////////////////////////////////////////////////
            if (counter == 1) //one check
            {

                DeleteRecord(words[0]);
                //Show some message box to clarify that the operation has been executed successfully.

            }
            /////////////////////////////////////////////////////////////
            if (counter > 1) //more than one check
            {
                for(int i=0; i<words.Count;i++)
                   {
                     DeleteRecord(words[i]);
                   }
                   //Show some message box to clarify that the operation has been executed successfully.
            }

            grdlistWord.DataBind();
        }

【讨论】:

  • 请在lnkbtnDelete 的事件处理程序上设置一个断点并告诉我wordsCount
  • 我正在使用验证,但我的页面上没有验证。
  • 我在 gridview 之外使用了链接按钮。. 使用 Cells[0] 进行复选框.. 你检查过我发布的代码吗??
  • 我想我解决了你的问题。在页面加载事件中:if (!IsPostBack) { grdlistWord.DataBind(); },而不是直接在页面加载中绑定。
【解决方案2】:

为此,您首先在表中设置了一个主键 ID,您将其作为 Grid 的源来获取。

绑定网格后,您应该将该 ID 保存在隐藏字段中。看下面的代码:

       <asp:GridView ID="gvwID" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="TableID">
           <Columns>
                <asp:TemplateField>
                     <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("TableID") %>'/>
                 <asp:TemplateField>
           </Columns>
       </asp:GridView>

然后在删除按钮点击事件中获取选中的行id:

        protected void Btn_Click(object sender, EventArgs e)
        {
                int[] OrderIDList = new int[gvwID.Rows.Count];

                int index = 0;

                 for (int count = 0; count < gvwID.Rows.Count; count++)
                 {
                   if (gvwID.Rows[count].FindControl("chkSelect") != null)
                    {
                       if (((CheckBox)gvwID.Rows[count].FindControl("chkSelect")).Checked)
                       {
                            if (gvwID.Rows[count].FindControl("HiddenField1") != null)
                            {
                            string OrderID = ((HiddenField)gvwID.Rows[count].FindControl("HiddenField1")).Value;
                        OrderIDList[index++] = Convret.ToInt32(OrderID);
                             }
                        }
                   }
        }

然后从 OrderIDList 创建一个附加字符串并将其传递给存储过程。从存储过程中使用附加的字符串创建一个 xml。遍历xml并获取每个id并执行删除。

请参阅以下程序:

              @IDList varchar(MAX)

            DECLARE @xmlUserIDs xml
    SELECT @xmlUserIDs = CONVERT(xml,'<root><cat>' +  REPLACE(@IDList,',','</cat><cat>') + '</cat></root>')// creates xml from appended string

    DELETE FROM  
        [TableName]
    WHERE 
    [TableID] IN (SELECT 
                    [Value] = T.C.value('.','int') 
                  FROM 
                    @xmlUserIDs.nodes('/root/cat') T(C));

希望对你有帮助..

【讨论】:

  • @Divya,OrderIDList 应该转换为带有分隔符的字符串(这里是逗号)。这对我有用..通常使用唯一 id(主键)对 db 中的特定记录执行任何更新/删除操作..
  • @Divya,检查这里的存储过程,它循环通过@xmlUserIDs并为每个id执行删除..
  • @Harun:我的存储过程成功完成。但请你能告诉我我应该在代码中执行这个存储过程的地方吗?
  • @Divya,您应该在删除按钮单击事件中执行代码。检查我的“Btn_Click”事件,我只是将选定的 id 提取到“int [] OrderIDList”。您需要将“OrderIDList”转换为逗号分隔的字符串,然后执行之后的过程(都在同一个按钮单击事件中)。
  • @Harun: 我这样做了 if (grdlistWord.Rows[count].FindControl("hfCount") != null) { string OrderID = ((HiddenField)grdlistWord.Rows[count].FindControl( "hfCount")). 值; OrderIDList[index++] = Convert.ToInt32(OrderID); SqlCommand cmd = 新的 SqlCommand(); cmd.CommandText = "[删除数据]"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Word", OrderIDList); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
相关资源
最近更新 更多