Prevent deletion of last row of GridView by disabling Delete Button in ASP.Net

Last Reply on May 16, 2014 12:14 AM By Azim

Posted on May 14, 2014 09:14 AM

There is a Gridview(say with 5 rows) in my web page with Delete button inside it.


I want that when I delete any row( say I deleted 5, 2, 3, 1) and then when I try to delete the last remaining row i.e., 4 then it should not get deleted.

I want that remaining any last row(can be any) in Grid should not get delete.

How to achieve that??

Please reply

Posted on May 16, 2014 12:14 AM

Refer this code

HTML

<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" DataKeyNames="Id" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Address" HeaderText="Address" ItemStyle-Width="150" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:Button ID="btnDelete" Text="Delete" OnClick="Delete" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Namespace

using System.Configuration;
using System.Data;
using System.Data.SqlClient;

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.PopulateEmployees();
        this.IsLastRow();
    }

}

private void IsLastRow()
{
    if (this.GridView1.Rows.Count == 1)
    {
        (this.GridView1.Rows[0].FindControl("btnDelete") as Button).Enabled = false;
    }
}

private void PopulateEmployees()
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", con))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();
                da.Fill(ds);
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }
}

protected void Delete(object sender, EventArgs e)
{
    string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
    GridViewRow gv = ((sender as Button).NamingContainer as GridViewRow);
    int id = Convert.ToInt32(this.GridView1.DataKeys[gv.RowIndex].Value);
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("DELETE FROM Employees WHERE Id = @Id", con))
        {
            cmd.Parameters.Add("@Id", id);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    Response.Redirect(Request.Url.AbsoluteUri);
}

Screenshot