ASP.NET - Gridview Edit and delete  ASP.NET - Gridview Edit and delete

Asked By Srinivasan S
18-Apr-11 06:02 AM
Hi,

I wanted to edit and update the GridView values in ASP.net with C#. Also wanted to delete the GridView row value. I found some examples in Google,but it doesnot give an exact idea.

So, Could anyone show me,how to do?

Thanks in advance!

Srini.
  TSN ... replied to Srinivasan S
18-Apr-11 06:07 AM
Hi....first have a templated GridView ..... as shown below

<asp:GridView ID="GV1" runat="server"  AllowPaging ="true" AllowSorting ="true" 
      AutoGenerateColumns="false"   OnRowEditing="GV1_RowEditingEvent"
      OnRowCommand ="GV1_RowCommandEvent"
      OnPageIndexChanging="GV1_PageIndexChangingEvent1"
      onselectedindexchanged="GV1_SelectedIndexChanged" >
   <Columns>
  <asp:TemplateField HeaderText="ProductId" >
  <ItemTemplate >
  <asp:Label ID="lblProductId" runat="server" Text='<%# Eval("ProductId") %>'  ></asp:Label>
  </ItemTemplate>
  <EditItemTemplate >
    <asp:Label ID="lblEditProductId" runat="server" Text='<%# Eval("ProductId") %>'  ></asp:Label>
  </EditItemTemplate>
  </asp:TemplateField>
 
  <asp:TemplateField HeaderText="ProductName" >
  <ItemTemplate >
  <asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>'  ></asp:Label>
  </ItemTemplate>
  <EditItemTemplate>
  <asp:TextBox ID="txtProductName" runat="server" Text='<%# Eval("ProductName") %>'></asp:TextBox>
  </EditItemTemplate>
  </asp:TemplateField>
 
  <asp:TemplateField HeaderText="QuantityPerUnit" >
   <ItemTemplate >
   <asp:Label ID="lblQuantityPerUnit" runat="server" Text='<%# Eval("QuantityPerUnit") %>'  ></asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
  <asp:TextBox ID="txtQuantityPerUnit" runat="server" Text='<%# Eval("QuantityPerUnit") %>'></asp:TextBox>
  </EditItemTemplate>
  </asp:TemplateField>
 
  <asp:TemplateField HeaderText="UnitPrice" >
  <ItemTemplate>
  <asp:Label ID="lblUnitPrice" runat="server" Text='<%# Eval("UnitPrice") %>'></asp:Label>
  </ItemTemplate>
  <EditItemTemplate>
  <asp:TextBox ID="txtUnitPrice" runat="server" Text='<%# Eval("UnitPrice") %>'></asp:TextBox>
  </EditItemTemplate>
  </asp:TemplateField>
 
  <asp:TemplateField HeaderText="Edit/Update" >
   <EditItemTemplate>
     <asp:ImageButton ID="Ibeditupdate" runat="server" ImageUrl="~/Images/icon-floppy.gif" CommandName="update" />
    </EditItemTemplate>
    <ItemTemplate>
    <asp:ImageButton ID="IbUpdate" runat="server" ImageUrl="~/Images/icon-pencil.gif" CommandName="edit" />
     </ItemTemplate>
  </asp:TemplateField>
  <asp:TemplateField HeaderText="Delete">
   <ItemTemplate>
   <asp:ImageButton ID="IbDelete" runat="server" ImageUrl="~/Images/icon-delete.gif" CommandName="delete1" />
    </ItemTemplate>
     <EditItemTemplate>
     <asp:ImageButton ID="Ibeditcancel" Height="10px" Width="10px" runat="server" ImageUrl="~/Images/Cancel.jpg" CommandName="cancel1" />
    </EditItemTemplate>
  </asp:TemplateField>
    
  </Columns>
  </asp:GridView>
After adding the above code .... now using the command events i mentioned for the buttons .... use this events in rowcommand event and do the required function.... by finding the control...

  public void GV1_RowCommandEvent(object sender, GridViewCommandEventArgs e)
  {     
 
    #region Delete
    if (e.CommandName == "delete1")
    
      //  string v=Convert .ToString (e.CommandArgument.ToString());
      int v = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).DataItemIndex;
      //Response.Write("You are going to delete : " + v);
      Label t1 = ((Label)GV1.Rows[v].FindControl("lblProductId"));
      int PId =Int32.Parse(t1.Text);
      string query1 = "Delete from dbo.[Order Details] where ProductId=" + PId;
      string query = "Delete from Products where ProductId=" + PId;
      SqlConnection conn1 = new SqlConnection(conn);
      conn1.Open();
 
      SqlCommand comm = new SqlCommand(query1, conn1);
      SqlDataReader dr = comm.ExecuteReader();
      conn1.Close();
      conn1.Open();
      SqlCommand comm1 = new SqlCommand(query, conn1);
      SqlDataReader dr1 = comm1.ExecuteReader();
      conn1.Close();
       GetData();
       }
#endregion
 
    #region Update
    else if (e.CommandName == "update1")
    {
      int v = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).DataItemIndex;
 
      Label t1 = ((Label)GV1.Rows[v].FindControl("lblEditProductId"));
      int id = Convert.ToInt32(t1.Text);
      TextBox t2 =(TextBox)GV1.Rows[v].FindControl("txtProductName");
      string sName = t2.Text;
       TextBox t3 = (TextBox)GV1.Rows[v].FindControl("txtQuantityperUnit");
       string QperUnit = t3.Text;
       TextBox t4= (TextBox)GV1.Rows[v].FindControl("txtUnitPrice");
       string unitprice = t4.Text;
      SqlConnection conn1 = new SqlConnection(conn);
      conn1.Open();
      //string query1 = "Delete from dbo.[Order Details] where ProductId=" + PId;
      string query1 = "update Products set ProductName='"+sName +"', QuantityPerUnit='" + QperUnit + "', UnitPrice='" + unitprice +"' where ProductId="+id ;
      string query2 = "update Products into (ProductName, QuantityPerUnit, UnitPrice)Values('"+sName +"','" + QperUnit + "','" + unitprice +"'");
      SqlCommand comm = new SqlCommand(query1, conn1);
      comm.ExecuteNonQuery();
      conn1.Close();
      GV1.EditIndex = -1;
      GetData();
      int discountId=Convert.ToInt32(GV1.SelectedRow.Cells[0].Text);
 
    }
    #endregion
       
    #region Cancel
    else if (e.CommandName == "cancel1")
    {
      int v = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).DataItemIndex;
      GV1.EditIndex = -1;
      GetData();
    }
    #endregion
  }
Hope this helps you... any doubts regarding this ping me back...
  Vickey F replied to Srinivasan S
18-Apr-11 06:08 AM


GridView Insert, Edit, Update and Delete

STEP  1: Creating  a DataBase Table

In this demo, I presumed that you already have a basic background on how to create a simple database table.
In this example, this time I used my own database called SampleDB which has Customers Table and basically
contains the following field columns:

CustomerID – PK

CompanyName

ContactName

ContactTitle

Address

Country

STEP 2: Setting Up the Connection String

 

    <connectionStrings>

      <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\SampleDB.mdf;
Integrated Security=True;User Instance=True
" providerName="System.Data.SqlClient"/>

    </connectionStrings>

 

 

STEP 3: Setting up the GUI

Just for the simplicity of this demo, I set up the GUI like this:

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>GridView Data Manipulation</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <table cellpadding="0" cellspacing="0">

      <tr>

      <td style="width: 100px; height: 19px;">

        Company ID</td>

      <td style="width: 100px; height: 19px;">

        Company</td>

      <td style="width: 100px; height: 19px;">

        Name</td>

      <td style="width: 100px; height: 19px;">

        Title</td>

      <td style="width: 100px; height: 19px;">

        Address</td>

      <td style="width: 100px; height: 19px;">

        Country</td>

      </tr>

      <tr>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox1" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox2" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox3" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox4" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox5" runat="server"/></td>

      <td style="width: 100px">

        <asp:TextBox ID="TextBox6" runat="server"/></td>

      <td style="width: 100px">

        <asp:Button ID="Button1" runat="server" Text="Add New" OnClick="Button1_Click" /></td>

      </tr>

    </table>

   

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowFooter="true">

    <Columns>

      <asp:BoundField DataField="CustomerID" HeaderText="ID" ReadOnly="true"/>

      <asp:BoundField DataField="CompanyName" HeaderText="Company"/>

      <asp:BoundField DataField="ContactName" HeaderText="Name"/>

      <asp:BoundField DataField="ContactTitle" HeaderText="Title" />

      <asp:BoundField DataField="Address" HeaderText="Address"/>

      <asp:BoundField DataField="Country" HeaderText="Country"/>

    </Columns>

    </asp:GridView>

    </div>

    </form>

</body>

</html>


Note:  I have set the CustomerID field to ReadOnly so that the field cannot be edited.

STEP 4: Binding GridView with Data

I will not elaborate on this step because I already describe the details in
my previous example about “Binding GridView with Data”. Here are the code
blocks for binding the GridView.

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    if (!IsPostBack)

    {

      BindGridView();

    }

    }

 

    private string GetConnectionString()

    {

    return System.Configuration.ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

    }

 

    #region Bind GridView

    private void BindGridView()

    {

    DataTable dt = new DataTable();

    SqlConnection connection = new SqlConnection(GetConnectionString());

    try

    {

      connection.Open();

      string sqlStatement = "SELECT Top(10)* FROM Customers";

        SqlCommand cmd = new SqlCommand(sqlStatement, connection);

        SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);

 

        sqlDa.Fill(dt);

        if (dt.Rows.Count > 0)

        {

      GridView1.DataSource = dt;

      GridView1.DataBind();

        }

    }

    catch (System.Data.SqlClient.SqlException ex)

    {

      string msg = "Fetch Error:";

      msg += ex.Message;

      throw new Exception(msg);

    }

    finally

    {

      connection.Close();

    }

    }

    #endregion

}

 

Now, we already know how to bind our GridView with data from database.
So let’s proceed on adding a new data in GridView.

STEP 5: Adding New Data in GridView

As you have noticed in STEP 2, we have added six TextBox and a Button
 in the web form in order for us to type the information there and Insert them
 to the database. Now let’s create a method for executing the Update or Insert.

Here are the code blocks for our Insert and Update method in the code behind:

 

#region Insert New or Update Record

    private void UpdateOrAddNewRecord(string ID, string Company, string Name, string Title,
string Address, string Country, bool isUpdate)

    {

    SqlConnection connection = new SqlConnection(GetConnectionString());

    string sqlStatement = string.Empty;

 

    if (!isUpdate)

    {

      sqlStatement = "INSERT INTO Customers"+

"(CustomerID,CompanyName,ContactName,ContactTitle,Address,Country)" +

"VALUES (@CustomerID,@CompanyName,@ContactName,@ContactTitle,@Address,@Country)";

    }

    else

    {

      sqlStatement = "UPDATE Customers" +

         "SET CompanyName = @CompanyName,

         ContactName = @ContactName," +

         "ContactTitle = @ContactTitle,Address = 

         @Address,Country = @Country" +

         "WHERE CustomerID = @CustomerID,";

    }

    try

    {

      connection.Open();

      SqlCommand cmd = new SqlCommand(sqlStatement, connection);

      cmd.Parameters.AddWithValue("@CustomerID", ID);

      cmd.Parameters.AddWithValue("@CompanyName", Company);

      cmd.Parameters.AddWithValue("@ContactName", Name);

      cmd.Parameters.AddWithValue("@ContactTitle", Title);

      cmd.Parameters.AddWithValue("@Address", Address);

      cmd.Parameters.AddWithValue("@Country", Country);

      cmd.CommandType = CommandType.Text;

      cmd.ExecuteNonQuery();

    }

    catch (System.Data.SqlClient.SqlException ex)

    {

      string msg = "Insert/Update Error:";

      msg += ex.Message;

      throw new Exception(msg);

 

    }

    finally

    {

      connection.Close();

    }

    }

    #endregion

 

The UpdateOrAddNewRecord is a method that takes seven parameters. 
Six of those paramaters basically comes from the TextBox values that were entered
 in the page. The last parameter is a boolean value which tells the method whether
 to execute an Insert (false) or Update (true). Default is true.

Here’s the code block for calling the method UpdateOrAddNewRecord on
Button_Click event and pass the corresponding parameters needed:

 

    protected void Button1_Click(object sender, EventArgs e)

    {

    UpdateOrAddNewRecord(TextBox1.Text, TextBox2.Text, TextBox3.Text, TextBox4.Text,
TextBox5.Text, TextBox6.Text, false);

    //Re Bind GridView to reflect changes made

    BindGridView();

    }

 

As you can see from above, We have called the BindGridView() method again in
 order to reflect the changes made and display the new added data in the GridView.
See output below with red mark.

 

STEP 6: Edit and Update Records In GridView

One of the good things about GridView is that it provides a built-in
 CommandField Buttons which allows us to perform certain actions like editing,
updating,deleting and selecting of GridView data.

To add those command fields mentioned in the GridView you can follow these
few steps below:

1.   Switch to Design View

2.   Right Click on the GridView and Select  --> Show Smart Tag
 --> Add New Columns

3.   On the List Select CommandField

4.   Check Delete and Edit/Update options then OK

 

As you can see the Edit and Delete CommandField are automatically
added in the last column of GridView.  Now we can start to write our codes
for editing and updating the information in the GridView.

 

In-order to perform Edit and Update in GridView we need to use three
 events ( GridView_RowEditing, GridView_RowCancelingEdit , GridView_RowUpdating).
For those who do not know on how to generate Events in GridView you can follow
these steps below:

 

1.   Switch to Design View in Visual Studio Designer

2.   Click on the GridView

3.   Navigate to the GridView Property Pane and then SWITCH to
Event Properties

4.   From there you would be able to find the list of events including
 those three  events mentioned above

5.   Double Click on that to generate the Event handler for you

6.   Then write the codes there

 

Here’s the code for each events:

 

 

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

    GridView1.EditIndex = e.NewEditIndex; // turn to edit mode

    BindGridView(); // Rebind GridView to show the data in edit mode

}

 

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

    GridView1.EditIndex = -1; //swicth back to default mode

    BindGridView(); // Rebind GridView to show the data in default mode

}

 

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

    //Accessing Edited values from the GridView

    string id = GridView1.Rows[e.RowIndex].Cells[0].Text; //ID

    string company = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text; //Company

    string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text; //Name

    string title = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text; //Title

    string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0]).Text; //Address

    string country = ((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text; //Country

 

    UpdateOrAddNewRecord(id,company,name,title,address,country,true); // call update method

    GridView1.EditIndex = -1;

    BindGridView(); // Rebind GridView to reflect changes made

}

 

STEP 7: Perform Delete in GridView

 

Since we are using the Built-in Delete CommandField Button in GridView,
 we can use the GridView_RowDeleting event to delete specific row in GridView.

 

Here’s the code block for the Delete method:

 

#region Delete Record

    private void DeleteRecord(string ID)

    {

    SqlConnection connection = new SqlConnection(GetConnectionString());

    string sqlStatement = "DELETE FROM Customers WHERE CustomerID = @CustomerID";

    try

    {

      connection.Open();

      SqlCommand cmd = new SqlCommand(sqlStatement, connection);

      cmd.Parameters.AddWithValue("@CustomerID", ID);

      cmd.CommandType = CommandType.Text;

      cmd.ExecuteNonQuery();

    }

    catch (System.Data.SqlClient.SqlException ex)

    {

      string msg = "Deletion Error:";

      msg += ex.Message;

      throw new Exception(msg);

 

    }

    finally

    {

      connection.Close();

    }

    }

#endregion

 

Here’s the code block for calling the delete method at RowDeleting event

 

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

   string id = GridView1.Rows[e.RowIndex].Cells[0].Text; get the id of the selected row

   DeleteRecord(id);//call delete method

   BindGridView();//rebind grid to reflect changes made

}


Now this code is visible for you, use it and let me know.
  Ravi S replied to Srinivasan S
18-Apr-11 06:12 AM
HI Srinivasan

I hope you will get full idea by this example of gridview

If GridView Control has Id="GridView1" then it generates the following event Handlers for these commands:

1. protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

2. protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

3. protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)


In properties winidow click on GridView1_RowEditing,GridView1_RowCancelingEdit


 protected void Page_Load(object sender, EventArgs e)
    {
      if (!IsPostBack)
        bindGridView();
    }

    public void bindGridView()
    {
      // string variable to store the connection string
      // defined in ConnectionStrings section of web.config file.
      string connStr = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

      // object created for SqlConnection Class.
      SqlConnection mySQLconnection = new SqlConnection(connStr);

      // if condition that can be used to check the sql connection
      // whether it is already open or not.
      if (mySQLconnection.State == ConnectionState.Closed)
      {
        mySQLconnection.Open();
      }

        SqlCommand mySqlCommand = new SqlCommand("SELECT CategoryID, CategoryName, Description FROM categories", mySQLconnection);
        SqlDataAdapter mySqlAdapter = new SqlDataAdapter(mySqlCommand);
        DataSet myDataSet = new DataSet();
        mySqlAdapter.Fill(myDataSet);

      GridView1.DataSource = myDataSet;
      GridView1.DataBind();


      // if condition that can be used to check the sql connection
      // if it is open then close it.
      if (mySQLconnection.State == ConnectionState.Open)
      {
        mySQLconnection.Close();
      }
    }

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
      GridView1.EditIndex = e.NewEditIndex;
      bindGridView();
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
      GridView1.EditIndex = -1;
      bindGridView();
}

For delete operation, follow the link below
http://programming.top54u.com/Samples/ASP-Net-cs/GridView-Control/GridView-CommandField-Delete-Command/Default.aspx
  Anoop S replied to Srinivasan S
18-Apr-11 06:18 AM


step 1 :

add CheckBox Column to your GridView first then you can delete Selected rows from GridView as well as Database like below code


Step 2 : Code

protected void btnDeleteSelected_Click(object sender, EventArgs e)
 {
   foreach (GridViewRow row in GridView1.Rows)
   {
 
   if (((CheckBox)row.FindControl("checkBox1")).Checked == true)
   {
   /* Get Table Id From Row */
   string id = GridView1.Rows[row.RowIndex].Cells[0].Text;
 
   /* delete from database */
 
   SqlConnection con = new SqlConnection("Connection String");
   con.Open();
 
   SqlCommand comm = new SqlCommand("delete from TableName where id='" + id + "'", con);
   comm.ExecuteNonQuery();
   }
   }
 
   /* Refresh the Grid */
   SqlConnection connc = new SqlConnection("Connection String");
   connc.Open();
 
   SqlCommand command = new SqlCommand("select * from TableName", connc);
   DataTable dt = new DataTable();
   SqlDataAdapter da = new SqlDataAdapter(command);
   da.Fill(dt);
   GridView1.DataSource = dt;
   connc.Close();
   DataBind();
 }

Same way you can update the data as well
  Reena Jain replied to Srinivasan S
18-Apr-11 06:20 AM
hi,

first add CheckBox Column to girdview and then use below code to delete the selected row from the girdview

protected void btnDelete_Click(object sender, EventArgs e)
 {
SqlConnection con = new SqlConnection("yourconnectionstring"); 
foreach (GridViewRow row in GridView1.Rows)
   {
   
   if (((CheckBox)row.FindControl("checkBox1")).Checked == true)
   {
   string myid = GridView1.Rows[row.RowIndex].Cells[0].Text;
     
   con.Open();
    SqlCommand comm = new SqlCommand("delete from table1 where id='" + myid + "'", con);
   comm.ExecuteNonQuery();
   }
   
 //rebind the gird with new data
   connc.Open();
 SqlCommand command = new SqlCommand("select * from TableName", connc);
   DataTable dt = new DataTable();
   SqlDataAdapter da = new SqlDataAdapter(command);
   da.Fill(dt);
   GridView1.DataSource = dt;
   connc.Close();
   DataBind();
   
 }

or use this code
01  protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
02    {
03    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
04    Label lbldeleteID = (Label)row.FindControl("lblid");
05    conn.Open();
06    SqlCommand cmd = new SqlCommand("delete  emp where rowid=" + lbldeleteID.Text + "", conn);
07    cmd.ExecuteNonQuery();
08    conn.Close();
09    //rebind the griview with updated data
10    }

Like this you can update the gridview also

Hope this will help you
  dipa ahuja replied to Srinivasan S
18-Apr-11 07:54 AM
You can do so by:

1. Take Gridview on your webpage.
2. Right Click on it , and choose "Add new Column" from that dialogBox select commandField from the combobox which will allow you to add "select, edit/update and delete" buttons on your GridView.


3.Now implement following events of Gridview

onrowcancelingedit="GridView1_RowCancelingEdit"

onrowdeleting="GridView1_RowDeleting" 

onrowediting="GridView1_RowEditing"

onrowupdating="GridView1_RowUpdating"



Full code:

<asp:GridView DataKeyNames="id" ID="GridView1" runat="server"

AutoGenerateColumns="false" EnableModelValidation="True"

onrowcancelingedit="GridView1_RowCancelingEdit"

onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"

onrowupdating="GridView1_RowUpdating">

 

     <Columns>

<asp:TemplateField HeaderText="Id">

  <ItemTemplate>

   <asp:Label ID="lblid" runat="Server" Text='<%# Eval("id") %>' />

  </ItemTemplate>

</asp:TemplateField>

 

<asp:TemplateField HeaderText="Name">

 <EditItemTemplate>

 <asp:TextBox Text='<%# Eval("name") %>'  ID="txtname" runat="server"></asp:TextBox>

    </EditItemTemplate>

    <ItemTemplate>

    <asp:Label ID="lblName" runat="Server" Text='<%# Eval("name") %>' />

 </ItemTemplate>

</asp:TemplateField>

 

<asp:CommandField ButtonType="Button" ShowDeleteButton="True" ShowEditButton="True"/>

</Columns>

</asp:GridView>

   

.CS Code

 

static string ConnString ="ConnectionString";

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

      //Code to bind gridview

    }

 

}

 

protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)

{

    GridView1.EditIndex = e.NewEditIndex;

    BindGrid();

}

protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)

{

    int id = int.Parse(((Label)GridView1.Rows[e.RowIndex].FindControl("lblid")).Text);//ID

    string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtname")).Text;

 

    SqlConnection connect = new SqlConnection(ConnString);

    connect.Open();

 

    string q = "Update people set name=@name where id=@id";

 

    SqlCommand comm = new SqlCommand(q, connect);

    comm.Parameters.AddWithValue("name", name);

    comm.Parameters.AddWithValue("id", id);

    comm.ExecuteNonQuery();

    connect.Close();

 

    GridView1.EditIndex = -1;

 

    BindGrid();

 

}

protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)

{

    GridView1.EditIndex = -1;

    BindGrid();

 

}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{

    int id = int.Parse(((Label)GridView1.Rows[e.RowIndex].FindContro("lblid")).Text);//ID

 

    SqlConnection connect = new SqlConnection(ConnString);

    connect.Open();

 

    string q = "Delete from table where id=@id";

 

    SqlCommand comm = new SqlCommand(q, connect);

    comm.Parameters.AddWithValue("id", id);

    comm.ExecuteNonQuery();

    connect.Close();

 

    GridView1.EditIndex = -1;

 

    BindGrid();

 

 

}

 

hope this will help you!

Create New Account
help
Fill(ds); GridView2.DataSource = ds; GridView2.DataBind(); } Code to delete protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e) { string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; / / FOR GETTING ENPID string deleteQuery Write("<script> alert('Record Deleted')< / script> "); getdata(); } Code to edit protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e) { GridView2.EditIndex = e.NewEditIndex; getdata(); } Code to Cancel protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView2.EditIndex = -1; getdata(); } Code to Update protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e) { string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; / / FOR GETTING ENPID string strEmpName new DataView ( CreateDGDataSource (), "ID = " + CategoryID , null , DataViewRowState . CurrentRows ); return dv ; } protected void GridView1_RowCommand ( object sender , GridViewCommandEventArgs e ) { try { if ( e . CommandName . Equals ( "New" )) { LinkButton btnNew = e . CommandSource as LinkButton ; GridViewRow row ASC" ; break ; case SortDirection . Descending : newSortDirection = "DESC" ; break ; } return newSortDirection ; } protected void GridView1_RowDeleting ( object sender , GridViewDeleteEventArgs e ) { int ID = ( int ) GridView1 . DataKeys [ e . RowIndex ]. Value ; / / Query the database and get the and delete it. lblMsg . Text = "Deleted Record Id" + ID . ToString (); } protected void GridView1_RowEditing ( object sender , GridViewEditEventArgs e ) { GridView1 . EditIndex = e . NewEditIndex ; BindGrid (); } protected void GridView1_RowUpdating ( object sender , GridViewUpdateEventArgs e ) { / / Retrieve the row being edited. int index = GridView1 . EditIndex ; GridViewRow row = GridView1 . Rows [ index
columncount; gvDetails2.Rows[0].Cells[0].Text = "No Records Found"; } } protected void gvDetails2_RowEditing(object sender, GridViewEditEventArgs e) { gvDetails2.EditIndex = e.NewEditIndex; BindBooksDetails(); } protected void gvDetails2_RowUpdating(object sender, GridViewUpdateEventArgs e) { / / string Call_Num = Convert.ToString(gvDetails2.DataKeys[e.RowIndex]["Call_Num"]); string Call_Num = gvDetails2.DataKeys[e lblresult.Text = Call_Num + " Details Updated successfully"; gvDetails2.EditIndex = -1; BindBooksDetails(); } protected void gvDetails2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { gvDetails2.EditIndex = -1; BindBooksDetails(); } protected void gvDetails2_RowDeleting(object sender, GridViewDeleteEventArgs e) { int call_num = Convert.ToInt32(gvDetails2.DataKeys[e.RowIndex].Values["Call_Num"].ToString()); string barcode_num = gvDetails2 lblresult.ForeColor = Color.Red; lblresult.Text = barcode_num + " details deleted successfully"; } } protected void gvDetails2_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("AddNew")) { TextBox txtCallNum = (TextBox)gvDetails2.FooterRow.FindControl("txtftrcallnum2"); TextBox txtBarcodeNum Fill(ds); GridView2.DataSource = ds; GridView2.DataBind(); } Code to delete protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e) { string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; / / FOR GETTING ENPID string deleteQuery Write("<script> alert('Record Deleted')< / script> "); getdata(); } Code to edit protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e) { GridView2.EditIndex = e.NewEditIndex; getdata(); } Code to Cancel protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView2.EditIndex = -1; getdata(); } Code to Update protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e
Fill(ds); GridView2.DataSource = ds; GridView2.DataBind(); } Code to delete protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e) { string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; / / FOR GETTING ENPID string deleteQuery Write("<script> alert('Record Deleted')< / script> "); getdata(); } Code to edit protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e) { GridView2.EditIndex = e.NewEditIndex; getdata(); } protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView2.EditIndex = -1; getdata(); } Code to Update protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e) { string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; / / FOR GETTING ENPID string strEmpName new DataView ( CreateDGDataSource (), "ID = " + CategoryID , null , DataViewRowState . CurrentRows ); return dv ; } protected void GridView1_RowCommand ( object sender , GridViewCommandEventArgs e ) { try { if ( e . CommandName . Equals ( "New" )) { LinkButton btnNew = e . CommandSource as LinkButton ; GridViewRow row ASC" ; break ; case SortDirection . Descending : newSortDirection = "DESC" ; break ; } return newSortDirection ; } protected void GridView1_RowDeleting ( object sender , GridViewDeleteEventArgs e ) { int ID = ( int ) GridView1 . DataKeys [ e . RowIndex ]. Value ; / / Query the database and get the and delete it. lblMsg . Text = "Deleted Record Id" + ID . ToString (); } protected void GridView1_RowEditing ( object sender , GridViewEditEventArgs e ) { GridView1 . EditIndex = e . NewEditIndex ; BindGrid (); } protected void GridView1_RowUpdating ( object sender , GridViewUpdateEventArgs e ) { / / Retrieve the row being edited. int index = GridView1 . EditIndex ; GridViewRow row = GridView1 . Rows [ index
Fill(ds); GridView2.DataSource = ds; GridView2.DataBind(); } Code to delete protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e) { string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; / / FOR GETTING ENPID string deleteQuery Write("<script> alert('Record Deleted')< / script> "); getdata(); } Code to edit protected void GridView2_RowEditing(object sender, GridViewEditEventArgs e) { GridView2.EditIndex = e.NewEditIndex; getdata(); } protected void GridView2_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GridView2.EditIndex = -1; getdata(); } Code to Update protected void GridView2_RowUpdating(object sender, GridViewUpdateEventArgs e) { string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text; / / FOR GETTING ENPID string strEmpName used to delete of the row record from the database protected void GridView1_RowDeleting( object sender, GridViewDeleteEventArgs e) { try { if (cnn.State = = ConnectionState.Closed) { cnn.Open(); } / / inside the id variable i am MapPath( "images" ) + " \ " + image); } catch { } cmd.ExecuteNonQuery(); cmd.Dispose(); grd_bind(); } catch { } } protected void GridView1_RowCancelingEdit( object sender, GridViewCancelEditEventArgs e) { GridView1.EditIndex = -1; grd_bind(); } protected void GridView1_RowEditing( object sender, GridViewEditEventArgs e) { GridView1.EditIndex = e.NewEditIndex; grd_bind(); } protected void GridView1_RowUpdating( object sender, GridViewUpdateEventArgs e) { if (cnn.State = = ConnectionState.Closed) { cnn.Open(); } / / inside the id variable i am finding