Home > Blockchain >  How to Delete a record from GridView using an external button
How to Delete a record from GridView using an external button

Time:12-29

I am trying to delete a record from grid. The case is, I am deleting a record from grid first only using link button inside gridview and after that user can click on an external button on the gridview only then record must be deleted from database. The issue is while deleting a record from grid first will make that particular record unavailable to delete after clicking an external button. I have attached code please look into this!

**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 >
    <form id="form1" runat="server">
    <section id="mian-content">
        <section id="wrapper">
            <section>
                <div >
                    <div >
                        <section >
                            <header >
                                <div  style="text-align:center" >
                                    <h3>Country and Cities Page</h3>
                                </div>
                            </header>
                            <div >
                                <div >
                                       
                                <div >
                                    <div >
                                        <div >
                                            <asp:Label ID="Label1" Text="Country Code" runat="server" />
                                            <asp:TextBox runat="server" Enabled="true" CssClass="form-control input-sm" placeholder="Enter Country Code"  ID="txCountryCode"/>
                                        </div>
                                    </div>

                                    <div >
                                        <div >
                                            <asp:Label ID="Label2" Text="Country Name" runat="server" />
                                            <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");
        }
    }
}

CodePudding user response:

Why not just drop in a plane jane asp button into the grid?

Wire up a click event, you are done!

I would not bother with the built in button.

Say we have this grid - and we drop in a button. (heck, lets get fancy, and put in a bootstrap icon for the button!!!).

So, we have this:

        <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 >
                      <asp:Button ID="cmdDelete" runat="server" Text="Delete" 
                        BackColor ="Transparent" BorderWidth="0"  />
                </div>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

to load the grid we have this:

   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();                    
            }
        }
    }

And now we have this:

enter image description here

Ok, now lets add a click event to that button.

(we can't double click on the button - since it inside of the GV).

So, in the markup type in OnClick= (AND NOTE VERY careful how you are offered to create a click event. eg this:

enter image description here

Select create new event - don't seem like much occurred - flip to code behind, and we can then write in our delete code for this button.

    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();
            }
        }
    }

I don't really see much of any advantage to trying to say use the built in GV button. Just drop in a button - wire up the delete code.

Edit:

Now, maybe you don't want a delete button for each row. You want say a check box on each row - you check the ones to delete, and BELOW the grid, you have a button "Delete Selected"

So, our markup now is this:

        <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 >
            <asp:Button ID="cmdDelete" runat="server" Text="Delete selected" 
            BackColor ="Transparent" BorderWidth="0" 
                OnClick="cmdDelete_Click" />
        </div>

Code to load grid - same as before. And our button? Well, just drop in a plane jane button outside of the grid. So we now have this:

enter image description here

And our code to delete selected can be this:

    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();
                    }
                }
            }               
        }
    }

CodePudding user response:

What I did is once user click an inside grid button, I store the remaining record of the gridView in ViewState["gridData"] and on the click event of an external button, I store that ViewState["gridData"] in Datatable and reinsert the record in database using for loop

  • Related