0

I have created a Asp.net web app with Grid View. I have populated the grid view by fetching data from my SQl DataBase. How to delete record from table by selecting it in the Grid View. I tried different methods but no use.

protected void LeaveGrid_SelectedIndexChanged(object sender, EventArgs e)
{
    GridViewRow row = LeaveGrid.SelectedRow; 
    DBConn dbcon = new DBConn();
    String qry = "Delete from Leave where  "What to give here ?"
    Boolean stat = dbcon.inserterrortrack(qry);
    if (stat == true)
    {
        Label1.Text = "Record Deleted Successfully";
    }
    else if (stat == false)
    {
        Label1.Text = "Delete Failed";
    }
    bind();
}

4 Answers 4

1
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    string id = GridView1.DataKeys[e.RowIndex].Values["Id"].ToString();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "Delete FROM TableName where Id='" + id + "'";
    cmd.Connection = con;
    con.Open();
    cmd.ExecuteNonQuery();
    con.Close();
    GetGridData();
    Response.Write("<script>alert('Module Deleted..!!!');</script>");
}

and on aspx page

<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" 
            GridLines="None" AutoGenerateColumns="False"
            DataKeyNames="Id" AllowPaging="True"                 
            onrowdeleting="GridView1_RowDeleting">   
            <Columns>
             <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                        <asp:Label ID="lblID" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>                               
                // here your other colums                   
                <asp:TemplateField HeaderText="Delete?">
                    <ItemTemplate>
                        <span onclick="return confirm('Are you sure to Delete the record?')">
                            <asp:LinkButton ID="lnkB" runat="Server" Text="Delete" CommandName="Delete"></asp:LinkButton>
                        </span>
                    </ItemTemplate>
                </asp:TemplateField>
    </Columns>          
            <AlternatingRowStyle BackColor="White" />
            <EditRowStyle BackColor="#2461BF" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#EFF3FB" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <sortedascendingcellstyle backcolor="#F5F7FB" />
            <sortedascendingheaderstyle backcolor="#6D95E1" />
            <sorteddescendingcellstyle backcolor="#E9EBEF" />
            <sorteddescendingheaderstyle backcolor="#4870BE" />
        </asp:GridView>

And for reference use that link:

Edit,update, delete gridview

Sign up to request clarification or add additional context in comments.

Comments

0

Can you add command link for delete in the grid for each row

A quick googling gave me this tutorial
http://www.c-sharpcorner.com/UploadFile/9f0ae2/gridview-edit-delete-and-update-in-Asp-Net/

Comments

0

If you are using Template field,

 protected void GridView1_RowDeleting(object sender, GridViewEditEventArgs e)
{  // you can retrieve the value of each row like
  Label lblRequestID=(Label)GridView1.Rows[e.NewEditIndex].FindControl("ControlID");
   Delete(lblRequestID.Text);
}

// you can use below code if u r using stored procedure

 public void Delete(string id)
    {

        CMD.Parameters.Clear();
        CMD.CommandText = "SP name";
        CMD.Parameters.AddWithValue("@ID", id);
        try
        {
            CON.Open();
            CMD.ExecuteReader();
        }
        catch (Exception ex)
        {
            Console.Write(ex.InnerException);
        }

        finally
        {
            CON.Close();
        }
    }

Comments

0

Your example code does not have valid T-SQL. Try this:

GridViewRow row = LeaveGrid.SelectedRow; 
DBConn dbcon = new DBConn();
int idToDelete = Convert.ToInt32(LeaveGrid.DataKeys[e.RowIndex].Value.ToString());
String qry = "Delete from Leave where id=" + idToDelete;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.