【问题标题】:How to Delete a record from GridView using an external button如何使用外部按钮从 GridView 中删除记录
【发布时间】:2021-12-27 07:51:30
【问题描述】:

我正在尝试从网格中删除一条记录。情况是,我首先只使用gridview中的链接按钮从网格中删除记录,然后用户可以单击gridview上的外部按钮,然后必须从数据库中删除记录。 问题是,首先从网格中删除记录将使该特定记录在单击外部按钮后无法删除。 我已附上代码,请查看!

**Aspx file:**



 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CountryService.aspx.cs"
    Inherits="CountryServiceApp.CountryService" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Country Website</title>
    <link href="css/bootstrap-grid.css" rel="stylesheet" type="text/css" />
    <link href="css/bootstrap-grid.min.css" rel="stylesheet" type="text/css" />
    <link href="css/bootstrap-reboot.css" rel="stylesheet" type="text/css" />
    <link href="css/bootstrap-reboot.min.css" rel="stylesheet" type="text/css" />
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css" />
    <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" />
    <a href="CountryService.aspx"></a>
    <script src="js/bootstrap.bundle.js" type="text/javascript"></script>
    <script src="js/bootstrap.bundle.min.js" type="text/javascript"></script>
    <script src="js/bootstrap.js" type="text/javascript"></script>
    <script src="js/bootstrap.min.js" type="text/javascript"></script>

</head>
<body>
<div class="container my-4">
    <form id="form1" runat="server">
    <section id="mian-content">
        <section id="wrapper">
            <section>
                <div class="row">
                    <div class="col-lg-12">
                        <section class="panel">
                            <header class="panel-heading">
                                <div class=" col-md-4 col-md-offset-4 text-center ml-3" style="text-align:center" >
                                    <h3>Country and Cities Page</h3>
                                </div>
                            </header>
                            <div class="panel-body">
                                <div class="container my-5">
                                       
                                <div class="row">
                                    <div class="col-md-5 col-md-offset-1">
                                        <div class="form-group">
                                            <asp:Label ID="Label1" Text="Country Code" runat="server" class="form-label"/>
                                            <asp:TextBox runat="server" Enabled="true" CssClass="form-control input-sm" placeholder="Enter Country Code"  ID="txCountryCode"/>
                                        </div>
                                    </div>

                                    <div class="col-md-5 col-md-offset-1">
                                        <div class="form-group">
                                            <asp:Label ID="Label2" Text="Country Name" runat="server" class="form-label"/>
                                            <asp:TextBox runat="server" Enabled="true" CssClass="form-control input-sm" ID="txtCountryName"/>
                                            </div>
                                        <br />
                                        <br />
                                  
                                  <%--onDelete--%>
                                  <%--btnDelete_Click --%>
                                    <asp:Button ID="btnFind" runat="server" Text="Find" CssClass="btn btn-info" 
                                            onclick="btnFind_Click"/>
                                         <asp:Button ID="btnSave" runat="server" Text="Save" CssClass="btn btn-primary" 
                                            onclick="btnSave_Click"/>
                                          <asp:Button ID="btnDelete" runat="server" Text="Delete" 
                                            CssClass="btn btn-danger" onclick="onDelete" OnClientClick="" />
                                              <asp:Button ID="btnUpdate" runat="server" Text="Update" 
                                            CssClass="btn btn-warning" onclick="btnUpdate_Click"/>
                                           <asp:Button ID="btnCancel" runat="server" Text="Cancel" 
                                            CssClass="btn btn-primary" onclick="btnCancel_Click"/>
                                         <br />
                                         <br />
   </div>
                                    </div>
                                </div>

                            </div>
                        </section>
                    </div>
                </div>
                <br />
                <br />
             <%-- OnRowDataBound = "OnRowDataBound" --%>   
             <%-- onrowupdating="gridCity_RowUpdating" --%>
        <asp:GridView ID="gridCity" runat="server" 
        GridLines="Vertical"  
        RowHeaderColumn="Action" 
        onrowdeleting="gridCity_RowDeleting" 
        CssClass="table table-bordered table-dark" 
        DataKeyNames="CityCode"
        onrowediting="gridCity_RowEditing" 
        AutoGenerateEditButton="false" onrowcancelingedit="gridCity_RowCancelingEdit"
        >
        <Columns>
        <asp:TemplateField HeaderText="Action">
         <ItemTemplate>
         <asp:CheckBox ID="chkSelect" runat="server"></asp:CheckBox>
          <asp:LinkButton ID="btnEdit" runat="server" Text="Edit" 
        CssClass="btn btn-warning" CommandName="Edit"></asp:LinkButton>
          <asp:Button ID="btnDeleteGrid" runat="server" Text="Delete" 
        CssClass="btn btn-danger" CommandName="Delete"></asp:Button>
            </ItemTemplate>
               <EditItemTemplate>    
                    <asp:LinkButton ID="LinkButton1" Text="Update" runat="server" CssClass="btn btn-warning" OnClick="OnUpdate" CommandName="Update"/>    
                    <asp:LinkButton ID="LinkButton2" Text="Cancel" runat="server" CssClass="btn btn-primary" CommandName="Cancel"/>    
                </EditItemTemplate> 
  
        </asp:TemplateField>
        </Columns>

                <AlternatingRowStyle BackColor="#DCDCDC" />
                <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
                <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
                <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
                <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
                <SortedAscendingCellStyle BackColor="#F1F1F1" />
                <SortedAscendingHeaderStyle BackColor="#0000A9" />
                <SortedDescendingCellStyle BackColor="#CAC9C9" />
                <SortedDescendingHeaderStyle BackColor="#000065" />
    </asp:GridView> 
            </section>
        </section>
    </section>
    </form>
    </div>
</body>
</html>
    
**Aspx.Cs file:**

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace CountryServiceApp
{
    public partial class CountryService : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnCancel.Enabled = false;
                btnDelete.Enabled = false;
                btnSave.Enabled = false;
                btnUpdate.Enabled = false;
            }
        }

        protected void btnFind_Click(object sender, EventArgs e)
        {
            try
            {
                countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
                countryService.Country c = client.Search(txCountryCode.Text);
                if (c != null)
                {
                    txtCountryName.Text = c.CountryName;
                    loadData();
                    btnCancel.Enabled = true;
                    btnDelete.Enabled = true;
                    btnSave.Enabled = true;
                    btnUpdate.Enabled = true;
                    btnFind.Enabled = true;
                }
                else
                {
                    Response.Write("Record does not exist");
                }

            }
            catch (Exception)
            {
                Response.Write("Record does not exist");
            }
        }

        protected void loadData()
        {

            DataTable dt = new DataTable();
            gridCity.Visible = true;
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spSelectCountryandCity", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter parameterId = new SqlParameter();
                parameterId.ParameterName = "@CountryCode";
                parameterId.Value = txCountryCode.Text;
                cmd.Parameters.Add(parameterId);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                //while (rdr.Read())
                //{
                //    gridCity.DataSource = rdr;
                //    gridCity.DataBind();
                //}
                if (rdr.HasRows)
                {
                    dt.Load(rdr);
                    gridCity.DataSource = dt;
                    gridCity.DataBind();
                    ViewState["gridData"] = dt;
                }
                else
                {
                    gridCity.Visible = false;
                }
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            txCountryCode.Text = txtCountryName.Text = string.Empty;
            gridCity.Visible = false;
            btnCancel.Enabled = false;
            btnDelete.Enabled = false;
            btnSave.Enabled = false;
            btnUpdate.Enabled = false;
            btnFind.Enabled = true;
        }

        
        protected void gridCity_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            DataTable dt = (DataTable)ViewState["gridData"];
            if (dt.Rows.Count > 0)
            {
                //DataRow index = dt.Rows[e.RowIndex];
                //Session["index"] = index;
                CheckBox chkSelect = (CheckBox)gridCity.Rows[e.RowIndex].FindControl("chkSelect");
                if (chkSelect.Checked == true)
                {
                    Session["chkSelect"] = chkSelect;   
                   // cityCode = Convert.ToString(gridCity.Rows[e.RowIndex].Cells[1].Text);
                }
                dt.Rows[e.RowIndex].Delete();
                dt.AcceptChanges();
                gridCity.DataSource = dt;
                gridCity.DataBind();
            }
            //txCountryCode.Text = txtCountryName.Text = string.Empty;
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
                countryService.Country c = new countryService.Country();
                c.CountryCode = txCountryCode.Text;
                c.CountryName = txtCountryName.Text;
                client.Insert(c);
                Response.Write("Country added in a table");
                loadData();
                btnFind.Enabled = true;
            }

            catch (Exception)
            {
                Response.Write("Record already exist");
            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
            client.Delete(txCountryCode.Text);
            Response.Write("Record of " + " " + txtCountryName.Text + " " + "Cities has been deleted");
            loadData();
            btnFind.Enabled = true;
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
            countryService.Country c = new countryService.Country();
            c.CountryCode = txCountryCode.Text;
            c.CountryName = txtCountryName.Text;
            client.Update(c);
            Response.Write("Country updated in a table");
            loadData();
            btnFind.Enabled = true;
        }

        protected void gridCity_RowEditing(object sender, GridViewEditEventArgs e)
        {
            gridCity.EditIndex = e.NewEditIndex;
            //loadData();           
        }

        protected void OnUpdate(object sender, EventArgs e)
        {
            GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
            //string CityCode=((TextBox)row.Cells[1].Controls[0]).Text;  
            string CityName = ((TextBox)row.Cells[2].Controls[0]).Text;
            //string CountryCode = ((TextBox)row.Cells[3].Controls[0]).Text;
            DataTable dt = ViewState["gridData"] as DataTable;
            //dt.Rows[row.RowIndex]["CityCode"] = CityCode;
            if (CityName != null && CityName != "")
            {
                dt.Rows[row.RowIndex]["CityName"] = CityName;
                //dt.Rows[row.RowIndex]["CountryCode"] = CountryCode;
                //dt.AcceptChanges();
                //dt.Rows[row.RowIndex].SetModified();
                ViewState["gridData"] = dt;
                gridCity.EditIndex = -1;
                gridCity.DataSource = dt;
                gridCity.DataBind();
            }
            else
            {
                Response.Write("Name field can not be empty");
            }
        }

        protected void gridCity_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            gridCity.EditIndex = -1;
            loadData();
        }

        protected void onDelete(object sender, EventArgs e)
        {

            //    foreach (GridViewRow grow in gridCity.Rows)
            //    {
            //         Button btn = (Button)grow.FindControl("btnDeleteGrid");
            //         //GridViewRow row = (sender as Button).NamingContainer as GridViewRow;
            //         DataTable dt = (DataTable)Session["index"];
            //         if (grow.RowIndex == 0)
            //          {
            //            //Convert.ToString(grow.Cells[1].Text);
            //            string cityCode = Convert.ToString(dt.Rows[1]["CityCode"]);
            //            countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
            //            client.DeleteCity(cityCode);
            //          }

            //        else
            //        {
            //            Response.Write("Error");
            //        }
            //    }
            //    //Displaying the Data in GridView  
            //    loadData();
            //    btnFind.Enabled = true;
            //}
            DataTable dt = (DataTable)ViewState["gridData"];
            gridCity.DataSource = dt;
            gridCity.DataBind();
            string cityCode = null;
            for (int i = 0; i <gridCity.Rows.Count ; i++)
            {
                CheckBox chkSelect = (CheckBox)gridCity.Rows[i].FindControl("chkSelect");
                chkSelect.Checked = true;
                //CheckBox chkSelect = (CheckBox)Session["chkSelect"];
                if (chkSelect.Checked == true)
                {
                    cityCode = Convert.ToString(gridCity.Rows[i].Cells[1].Text);
                    countryService.CountryServiceClient client = new countryService.CountryServiceClient("CountryService");
                    client.DeleteCity(cityCode);
                }
            }
            loadData();
            Response.Write("Record Deleted");
        }
    }
}

【问题讨论】:

  • 也许你可以看看this post并找到解决方案。

标签: asp.net gridview webforms


【解决方案1】:

为什么不直接将平面简 asp 按钮放到网格中?

连接一个点击事件,你就完成了!

我不会打扰内置按钮。

假设我们有这个网格 - 我们放入一个按钮。 (哎呀,让我们花点心思,为按钮添加一个引导图标!!!)。

所以,我们有这个:

        <asp:GridView ID="GHotels" runat="server" CssClass="table"
            width="50%" AutoGenerateColumns="False" DataKeyNames="ID" >
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"     />
                <asp:BoundField DataField="LastName" HeaderText="LastName"       />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName"     />
                <asp:BoundField DataField="City" HeaderText="City"               />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                     <div class="btn btn-default glyphicon glyphicon-trash">
                      <asp:Button ID="cmdDelete" runat="server" Text="Delete" 
                        BackColor ="Transparent" BorderWidth="0"  />
                </div>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

要加载网格,我们有这个:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadGrid();
    }

    void LoadGrid()
    {
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            string strSQL = "SELECT * FROM tblHotels ORDER BY HotelName";
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                DataTable rst = new DataTable();
                rst.Load(cmdSQL.ExecuteReader());
                GHotels.DataSource = rst;
                GHotels.DataBind();                    
            }
        }
    }

现在我们有了这个:

好的,现在让我们为该按钮添加一个点击事件。

(我们不能双击按钮 - 因为它在 GV 内部)。

因此,在 OnClick= 中的标记类型中(并注意非常小心地为您提供创建点击事件的方式。例如:

选择创建新事件 - 似乎没有发生太多 - 翻转到后面的代码,然后我们可以为这个按钮编写删除代码。

    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        Button cmdDel = sender as Button;
        GridViewRow gRow = cmdDel.NamingContainer as GridViewRow;
        int? pkID = GHotels.DataKeys[gRow.RowIndex]["ID"] as int?;

        string strSQL = "DELETE FROM tblHotels WHERE ID = " + pkID;
        using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
        {
            using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
            {
                conn.Open();
                cmdSQL.ExecuteNonQuery();
                // now re-fresh grid
                LoadGrid();
            }
        }
    }

我并没有真正看到尝试使用内置 GV 按钮有什么好处。只需按下一个按钮 - 连接删除代码。

编辑:

现在,也许您不想为每一行添加一个删除按钮。您想在每一行上说一个复选框 - 您选中要删除的复选框,在网格下方,您有一个“删除所选”按钮

所以,我们现在的标记是这样的:

        <asp:GridView ID="GHotels" runat="server" CssClass="table"
            width="50%" AutoGenerateColumns="False" DataKeyNames="ID" >
            <Columns>
                <asp:BoundField DataField="FirstName" HeaderText="FirstName"     />
                <asp:BoundField DataField="LastName" HeaderText="LastName"       />
                <asp:BoundField DataField="HotelName" HeaderText="HotelName"     />
                <asp:BoundField DataField="City" HeaderText="City"               />
                <asp:BoundField DataField="Description" HeaderText="Description" />
                <asp:TemplateField HeaderText = "Delete" ItemStyle-HorizontalAlign ="Center" >
                    <ItemTemplate>
                        <asp:CheckBox ID="chkSel" runat="server" CssClass="bigcheck" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <div class="btn btn-default glyphicon glyphicon-trash">
            <asp:Button ID="cmdDelete" runat="server" Text="Delete selected" 
            BackColor ="Transparent" BorderWidth="0" 
                OnClick="cmdDelete_Click" />
        </div>

加载网格的代码 - 与以前相同。我们的按钮呢?好吧,只需在网格外放一个平面简按钮。所以我们现在有了这个:

我们删除选中的代码可以是这样的:

    protected void cmdDelete_Click(object sender, EventArgs e)
    {
        string sDelList = "";
        foreach (GridViewRow gRow in GHotels.Rows)
        {
            CheckBox chkSel = gRow.FindControl("chkSel") as CheckBox;
            if (chkSel.Checked)
            {
                int? pkID = GHotels.DataKeys[gRow.RowIndex]["ID"] as int?;
                if (sDelList != "")
                    sDelList += ",";
                sDelList += pkID;
            }

            // delete selected
            if (sDelList != "")
            {
                string strSQL = "DELETE FROM tblHotels WHERE ID IN(" + sDelList + ")";
                using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
                {
                    using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
                    {
                        conn.Open();
                        cmdSQL.ExecuteNonQuery();
                        // now re-fresh grid
                        LoadGrid();
                    }
                }
            }               
        }
    }

【讨论】:

  • 因为,它要求客户端在 GridView 中也有一个按钮,单击该按钮记录后只会从 Gridview 中删除,而不是从数据库中删除,从数据库中删除一行后,您可以单击外部按钮,然后才会从数据库中删除记录。
  • 好的,所以我们需要一个行复选框来删除。请参阅我的编辑。我当然也会在按钮上添加一个“确认”对话框。
  • 确认!非常感谢您的回复。
【解决方案2】:

我所做的是,一旦用户单击内部网格按钮,我将 gridView 的剩余记录存储在 ViewState["gridData"] 中,在外部按钮的单击事件中,我将 ViewState["gridData"] 存储在 Datatable 中并将记录重新插入使用for循环的数据库

【讨论】:

  • 如果他们点击了错误的行 - 他们可以取消选择吗?如前所述,按照上面的简单复选框可能比每行上的删除按钮更好 - 除非您突出显示选择删除的每一行 - 用户将无法改变主意,并且很难看到/知道哪些行被标记为删除。但是,如果该 UI 适合您,那就没问题了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 2018-12-07
  • 2022-09-23
  • 1970-01-01
  • 2019-04-12
相关资源
最近更新 更多