[c#] How to delete a row from GridView?

I am using GridView control in 2005 using .

How can I delete a particular row from GridView.

I have written the following code. But it's not working...

DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();

int iCount = GVGLCode.Rows.Count;
for (int i = 0; i <= iCount; i++)
{
    GVGLCode.DeleteRow(i);
}
GVGLCode.DataBind();

This question is related to c# asp.net gridview delete-row

The answer is


You are deleting the row from the gridview but you are then going and calling databind again which is just refreshing the gridview to the same state that the original datasource is in.

Either remove it from the datasource and then databind, or databind and remove it from the gridview without redatabinding.


The default answer is to remove the item from whatever collection you're using as the GridView's DataSource.

If that option is undesirable then I recommend that you use the GridView's RowDataBound event to selectively set the row's (e.Row) Visible property to false.


Delete the row from the table dtPrf_Mstr rather than from the grid view.


Please try this code.....

DataRow dr = dtPrf_Mstr.NewRow();
dtPrf_Mstr.Rows.Add(dr);
GVGLCode.DataSource = dtPrf_Mstr;
GVGLCode.DataBind();
int iCount = GVGLCode.Rows.Count;
for (int i = 0; i < iCount; i++)
{
   GVGLCode.Rows.Remove(GVGLCode.Rows[i]);
}
GVGLCode.DataBind();

You're deleting the row from the gridview and then rebinding it to the datasource (which still contains the row). Either delete the row from the datasource, or don't rebind the gridview afterwards.


hi how to delete from datagridview

1.make query delete by id
2.type

tabletableadaptor.delete
query(datagridwiewX1.selectedrows[0].cell[0].value.tostring);

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Default3 : System.Web.UI.Page
{
   DataTable dt = new DataTable();
    DataSet Gds = new DataSet();
   // DataColumn colm1 = new DataColumn();
   //DataColumn colm2 = new DataColumn();

    protected void Page_Load(object sender, EventArgs e)
    {
        dt.Columns.Add("ExpId", typeof(int));
        dt.Columns.Add("FirstName", typeof(string));

    }


    protected void BtnLoad_Click(object sender, EventArgs e)
    {
        //   gvLoad is Grid View Id
        if (gvLoad.Rows.Count == 0)
        {
            Gds.Tables.Add(tblLoad());
        }
        else
        {
            dt = tblGridRow();
            dt.Rows.Add(tblRow());
            Gds.Tables.Add(dt);
        }
        gvLoad.DataSource = Gds;
        gvLoad.DataBind();
    }

    protected DataTable tblLoad()
    {
        dt.Rows.Add(tblRow());
        return dt;
    }
    protected DataRow tblRow()
    {
        DataRow dr;
        dr = dt.NewRow();
        dr["Exp Id"] = Convert.ToInt16(txtId.Text);
        dr["First Name"] = Convert.ToString(txtName.Text);
        return dr;
    }

    protected DataTable tblGridRow()
    {
        DataRow dr;
        for (int i = 0; i < gvLoad.Rows.Count; i++)
        {
            if (gvLoad.Rows[i].Cells[0].Text != null)
            {

                dr = dt.NewRow();
                dr["Exp Id"] = gvLoad.Rows[i].Cells[1].Text.ToString();
                dr["First Name"] = gvLoad.Rows[i].Cells[2].Text.ToString();
                dt.Rows.Add(dr);

            }

        }
        return dt;
    }

    protected void btn_Click(object sender, EventArgs e)
    {
        dt = tblGridRow();
        dt.Rows.Add(tblRow());
        Session["tab"] = dt;
        // Response.Redirect("Default.aspx");
    }

    protected void gvLoad_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        dt = tblGridRow();
        dt.Rows.RemoveAt(e.RowIndex);
        gvLoad.DataSource = dt;
        gvLoad.DataBind();
    }
}

My solution:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    myobj.myconnection();// connection created
    string mystr = "Delete table_name where water_id= '" + GridView1.DataKeys[e.RowIndex].Value + "'";// query
    sqlcmd = new SqlCommand(mystr, myobj.mycon);
    sqlcmd.ExecuteNonQuery();
    fillgrid();
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to gridview

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView) Android Recyclerview GridLayoutManager column spacing Get the cell value of a GridView row add new row in gridview after binding C#, ASP.net Check if list is empty in C# How to refresh Gridview after pressed a button in asp.net Putting GridView data in a DataTable How to get row data by clicking a button in a row in an ASP.NET gridview Change header text of columns in a GridView Twitter Bootstrap and ASP.NET GridView

Examples related to delete-row

Difference between Destroy and Delete How to delete a certain row from mysql table with same column values? Delete a row from a SQL Server table Deleting records before a certain date Deleting Row in SQLite in Android Deleting specific rows from DataTable deleting rows in numpy array Delete all data in SQL Server database Deleting rows with MySQL LEFT JOIN SQL DELETE with JOIN another table for WHERE condition