Edit Update data in Grdiview with Boundfield column in asp.net(c# & Vb.net).

Aman Sharma
4
Introduction:
In this article I will explain howe to edit and update data in gridview using Boundfield Coumns. I will use boundfield column  to bind gridview with database. Now I will perform edit and update operation.
Description:

In previous articles I have explained Bind, Update and delete data from Gridview in Asp.Net using C# and VB.net And  Implementation of Page Index or Paging in Gridview Control In asp.net (c# & Vb.net) And How to Populate or Fill Dataset with data from Database in asp.net using c# & Vb.net And Use Gridviews Template field to display data in asp.net(c# & vb.net) And Display data in Gridview using boundField in asp.net(c#, VB.net.

Follow these steps:
1.      Bind Gridview with database
2.      Add events i.e.  RowCancelingEdit, RowEditing, RowUpdating.
3.      Now write code to update data from gridview as given below.

Implementation:

 GridView Design:
<fieldset style="width:280px"><legend><strong>Edit Update & Delete in Gridview</strong></legend>
    <div>
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
            CellPadding="3" DataKeyNames="Student_ID" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" >
            <Columns>
                <Columns>
                <asp:BoundField DataField="Student_name" HeaderText="Name" />
                <asp:BoundField DataField="age" HeaderText="Age" />
                <asp:BoundField DataField="class" HeaderText="Class" />
                <asp:CommandField ShowEditButton="True" />
                </Columns>
            <FooterStyle BackColor="White" ForeColor="#000066" />
            <HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
            <RowStyle ForeColor="#000066" />
            <SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#007DBB" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#00547E" />
        </asp:GridView>
<br />
<br />
    </div>
    </fieldset>


1.     ASP.NET code behind File using C#:
In code behind, add following code:
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Configuration;

Now write code to Bind, update and Delete data from gridview:

public partial class gridview : System.Web.UI.Page
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e) 
    {
        if (!IsPostBack)
        {
            Fill_Grid();
        }
    }
    //Fetch data from database and bind to gridview
    public void Fill_Grid()
    {     
        if (con.State == ConnectionState.Open)
        {
            con.Close();
        }
        con.Open();
        DataSet ds = new DataSet();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "Fill_Dataset";
        cmd.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter dataadapater = new SqlDataAdapter();
    dataadapater.SelectCommand = cmd;
        dataadapater.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
        cmd.Dispose();
        con.Close();
    }

    //Edit data in gridview

    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        Fill_Grid();
       
    }
    //update data in gridview
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
        TextBox txtName = (TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0];
        TextBox txtAge = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
        TextBox txtClass = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
        if (con.State == ConnectionState.Open)
        {
            con.Close();       
        }
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "update student_info set Student_name=@name, age=@age, class=@class where student_id=@id";
        cmd.Parameters.AddWithValue("@name", txtName.Text);
        cmd.Parameters.AddWithValue("@age", txtAge.Text);
        cmd.Parameters.AddWithValue("@class", txtClass.Text);
        cmd.Parameters.AddWithValue("@id", id);
        cmd.ExecuteNonQuery();
        cmd.Dispose();
       
        con.Close();
        GridView1.EditIndex = -1;
        Fill_Grid();
        Response.Write("<script> alert('Record updated successfully')</script>");
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        Fill_Grid();
    }
}

VB.NET code behind file:
In code behind, add following code:
ImportsSystem.Data
ImportsSystem.Data.SqlClient
ImportsSystem.Configuration

Bind, Update and delete data from gridview:
Partial Public Class gridview
    Inherits System.Web.UI.Page
    Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("con").ConnectionString)
    Protected Sub Page_Load(sender As Object, e As EventArgs)
        If Not IsPostBack Then
            Fill_Grid()
        End If
    End Sub
    'Fetch data from database and bind to gridview
    Public Sub Fill_Grid()
        If con.State = ConnectionState.Open Then
            con.Close()
        End If
        con.Open()
        Dim ds As New DataSet()
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandText = "Fill_Dataset"
        cmd.CommandType = CommandType.StoredProcedure
        Dim dataadapater As New SqlDataAdapter()
        dataadapater.SelectCommand = cmd
        dataadapater.Fill(ds)
        GridView1.DataSource = ds
        GridView1.DataBind()
        cmd.Dispose()
        con.Close()
    End Sub

    'Edit data in gridview

    Protected Sub GridView1_RowEditing(sender As Object, e As GridViewEditEventArgs)
        GridView1.EditIndex = e.NewEditIndex
        Fill_Grid()

    End Sub

    'update data in gridview

    Protected Sub GridView1_RowUpdating(sender As Object, e As GridViewUpdateEventArgs)
        Dim id As Integer = Convert.ToInt32(GridView1.DataKeys(e.RowIndex).Value.ToString())
Dim txtName As TextBox = DirectCast(GridView1.Rows(e.RowIndex).Cells(0).Controls(0), TextBox)
Dim txtAge As TextBox = DirectCast(GridView1.Rows(e.RowIndex).Cells(1).Controls(0), TextBox)
Dim txtClass As TextBox = DirectCast(GridView1.Rows(e.RowIndex).Cells(2).Controls(0), TextBox)
        If con.State = ConnectionState.Open Then
            con.Close()
        End If
        con.Open()
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandText = "update student_info set Student_name=@name, age=@age, class=@class where student_id=@id"
        cmd.Parameters.AddWithValue("@name", txtName.Text)
        cmd.Parameters.AddWithValue("@age", txtAge.Text)
        cmd.Parameters.AddWithValue("@class", txtClass.Text)
        cmd.Parameters.AddWithValue("@id", id)
        cmd.ExecuteNonQuery()
        cmd.Dispose()

        con.Close()
        GridView1.EditIndex = -1
        Fill_Grid()
        Response.Write("<script> alert('Record updated successfully')</script>")
    End Sub
    Protected Sub GridView1_RowCancelingEdit(sender As Object, e As GridViewCancelEditEventArgs)
        GridView1.EditIndex = -1
        Fill_Grid()
    End Sub
End Class

Demo:


Use this code, create your own application and check result. You can use this code in any application by customizing it. If you have any doubt, you can ask by commenting in comment section.



Post a Comment

4Comments
  1. Hi.....

    How do you connect your DB to your application?

    ReplyDelete
    Replies
    1. Hi Xavier... In webconfig file.. using connection strings.... As given below:



      Delete
  2. Hey i get an error stating . Object reference not set to instance of an object near the textbox name = gridview 1. Cells statement pls help

    ReplyDelete
    Replies
    1. Can you please share your code or line where you are getting error?

      Delete
Post a Comment

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !