简体   繁体   中英

Deleting record from database is not working in GridView

I am trying to delete a record from my database by selecting the tick box and then click on delete. What seems to happen now is that the page refreshes but the entry is not being deleted. There are no error messages what so ever

I have followed this tutorial Delete Records From Gridview Using CheckBox in ASP.Net

This is what my code looks like:

AddIPAddress.aspx

<script type="text/javascript">  

    function DeleteConfirm() {
        var Ans = confirm("Do you want to Delete Selected Employee Record?");
        if (Ans) {
            return true;
        }
        else {
            return false;
        }
    }
</script>  

 <asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
            RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
            runat="server" AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="chkDel" runat="server" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField DataField="EmpId" HeaderText="Device Id" />
                <asp:BoundField DataField="Device" HeaderText="Device Name" />
                <asp:BoundField DataField="IP" HeaderText="IP Address" />
            </Columns>
            <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
            <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
            <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
            <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
            <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#FFF1D4" />
            <SortedAscendingHeaderStyle BackColor="#B95C30" />
            <SortedDescendingCellStyle BackColor="#F1E5CE" />
            <SortedDescendingHeaderStyle BackColor="#93451F" />
        </asp:GridView>
    </div> 
        <br />
        <asp:Button ID="btnDeleteRecord" runat="server" onclick="btnDeleteRecord_Click" Text="Delete" CssClass="btn-success" />

Then in:

AddIPAddress.cs.aspx

string cs = ConfigurationManager.ConnectionStrings["IPAddress"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
    {
        this.BindGrid();
        btnDeleteRecord.Attributes.Add("onclick", "javascript:return DeleteConfirm()");
    }

private void BindGrid()
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(cs);
        SqlDataAdapter adapt = new SqlDataAdapter("SELECT * FROM IPAddress", con);
        con.Open();
        adapt.Fill(dt);
        con.Close();
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    protected void OnPageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        this.BindGrid();
    }

    protected void DeleteRecord(int empid)
    {
        SqlConnection con = new SqlConnection(cs);
        SqlCommand com = new SqlCommand("DELETE FROM IPAddress WHERE EmpId=@ID", con);
        com.Parameters.AddWithValue("@ID", empid);
        con.Open();
        com.ExecuteNonQuery();
        con.Close();
    }

    protected void btnDeleteRecord_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow grow in GridView1.Rows)
        {
            //Searching CheckBox("chkDel") in an individual row of Grid  
            CheckBox chkdel = (CheckBox)grow.FindControl("chkDel");
            //If CheckBox is checked than delete the record with particular empid  
            if (chkdel.Checked)
            {
                int empid = Convert.ToInt32(grow.Cells[1].Text);
                DeleteRecord(empid);
            }
        }
        //Displaying the Data in GridView  
        BindGrid();
    }

Have I missed something?

Thanks

You need to do following this steps:-

I am explain you all the Process Deleting record from database is not working in GridView

 protected void btnDeleteRecord_Click(object sender, EventArgs e)  
   {    
    foreach (GridViewRow gvrow in GridView1.Rows)  
    {    
         var Label = gvrow.FindControl("Label1") as Label;  

           SqlCommand cmd = new SqlCommand("delete from tblname where id=@id",con);  
           cmd.Parameters.AddWithValue("id", int.Parse(Label.Text));  
            con.Open();  
            int id = cmd.ExecuteNonQuery();  
            con.Close();  
            refreshdata();  
        }  
    }

    public void refreshdata()  
    {   
      SqlCommand cmd = new SqlCommand("select * from tbl_data", con);  
      SqlDataAdapter sda = new SqlDataAdapter(cmd);  
      DataTable dt = new DataTable();  
      sda.Fill(dt);  
      GridView1.DataSource = dt;  
      GridView1.DataBind();
    }

Okay, I definitely missed something here:-)

This code here should be changed from:

protected void Page_Load(object sender, EventArgs e)
{
    this.BindGrid();
    btnDeleteRecord.Attributes.Add("onclick", "javascript:return DeleteConfirm()");
}

To

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Displaying the Data  
            BindGrid();
            //Adding an Attribute to Server Control(i.e. btnDeleteRecord)  
            btnDeleteRecord.Attributes.Add("onclick", "javascript:return DeleteConfirm()");
        }
    }

All is working now. Thanks to everyone who assisted:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM