Friday, May 3, 2013

How to Bind,Edit,Update,Pagination and Delete in Gridview in Asp.net?


Introduction: In this post I will tell you how to bind, edit, update and delete the Gridview data control in Asp.net.

Description:
I have created a table name STUDENT_DETAIL and insert data into table.
STUDENT_ID
int
STUDENT_NAME
varchar(50)
STUDENT_ADDRESS
varchar(50)
STUDENT_CLASS
varchar(50)

STUDENT_ID is primary key.
Now open the Visual Studio>Go to File>New>Website. Add the Connectionstring in web.config file of website.
<configuration>
       <connectionStrings>
    <add name="connection" connectionString="Data Source=SYS-1F78031ED0A;Initial Catalog=TestBlog;Integrated Security=True"/>
       </connectionStrings>
       <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>


After that add new web form to website, drag and drop the Gridview data control from Toolbox. After that add the Template field and ItemTemplate in Gridview as structure mention below.

  <asp:GridView ID="grdstudentdetail" runat="server" AutoGenerateColumns="False"
            DataKeyNames="STUDENT_ID"
            onrowcancelingedit="grdstudentdetail_RowCancelingEdit"
            onrowdeleting="grdstudentdetail_RowDeleting"
            onrowediting="grdstudentdetail_RowEditing"
            onrowupdating="grdstudentdetail_RowUpdating" AllowPaging="True"
            onpageindexchanging="grdstudentdetail_PageIndexChanging">
            <Columns>
                <asp:TemplateField HeaderText="STUDENT NAME">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtname" runat="server" Text='<%# Eval("STUDENT_NAME") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblname" runat="server" Text='<%# Eval("STUDENT_NAME") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="STUDENT ADDRESS">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtaddress" runat="server" Text='<%# Eval("STUDENT_ADDRESS") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lbladdress" runat="server" Text='<%# Eval("STUDENT_ADDRESS") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="STUDENT CLASS">
                    <EditItemTemplate>
                        <asp:TextBox ID="txtclass" runat="server" Text='<%# Eval("STUDENT_CLASS") %>'></asp:TextBox>
                    </EditItemTemplate>
                    <ItemTemplate>
                        <asp:Label ID="lblclass" runat="server" Text='<%# Eval("STUDENT_CLASS") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:CommandField ShowEditButton="True" />
                <asp:CommandField ShowDeleteButton="True" />
            </Columns>
        </asp:GridView>

Now go to .aspx.cs page and add namespace.
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        if (!IsPostBack)
        {
            Bindgridview();
        }
    }
    private void Bindgridview()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from STUDENT_DETAIL", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                grdstudentdetail.DataSource = dt;
                grdstudentdetail.DataBind();
            }
            else
            {
                dt.Rows.Add(dt.NewRow());
                grdstudentdetail.DataSource = dt;
                grdstudentdetail.DataBind();
                int columncount = grdstudentdetail.Rows[0].Cells.Count;
                grdstudentdetail.Rows[0].Cells.Clear();
                grdstudentdetail.Rows[0].Cells.Add(new TableCell());
                grdstudentdetail.Rows[0].Cells[0].ColumnSpan = columncount;
                grdstudentdetail.Rows[0].Cells[0].Text = "No Records Available
";
            }
        }
        catch (Exception ex)
        {
        }
    }
After that go to Gridview Properties>Events and double click one by one on RowEditing, RowCancelingEdit, RowUpdating and RowDeleting that will redirect you to .aspx.cs page. Write the code for each events.
protected void grdstudentdetail_RowEditing(object sender, GridViewEditEventArgs e)
    {
        grdstudentdetail.EditIndex = e.NewEditIndex;
        Bindgridview();
    }
    protected void grdstudentdetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        try
        {
            int STUDENT_ID = Convert.ToInt32(grdstudentdetail.DataKeys[e.RowIndex].Value.ToString());
            TextBox txtname = (TextBox)grdstudentdetail.Rows [e.RowIndex].FindControl("txtname");
            TextBox txtaddress = (TextBox)grdstudentdetail.Rows [e.RowIndex].FindControl("txtaddress");
            TextBox txtclass = (TextBox)grdstudentdetail.Rows[e.RowIndex].FindControl("txtclass");
            string update = "Update STUDENT_DETAIL set STUDENT_NAME ='" + txtname.Text + "', STUDENT_ADDRESS ='" + txtaddress.Text + "',STUDENT_CLASS= '" + txtclass.Text + "' where STUDENT_ID="+STUDENT_ID;
            SqlCommand cmd = new SqlCommand(update, con);
            cmd.ExecuteNonQuery();
            grdstudentdetail.EditIndex = -1;
            Response.Write("Record Update Successfully");
            Bindgridview();
        }
        catch (Exception ex)
        {
        }
    }
    protected void grdstudentdetail_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdstudentdetail.EditIndex = -1;
        Bindgridview();
    }
    protected void grdstudentdetail_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        try
        {
            int STUDENT_ID = Convert.ToInt32(grdstudentdetail.DataKeys[e.RowIndex].Value.ToString());
            string delete = "Delete from STUDENT_DETAIL where STUDENT_ID=" + STUDENT_ID;
            SqlCommand cmd = new SqlCommand(delete, con);
            cmd.ExecuteNonQuery();
            Response.Write("Record Delete Successfully");
            Bindgridview();
        }
        catch (Exception ex)
        {
        }
    }

 protected void grdstudentdetail_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdstudentdetail.PageIndex = e.NewPageIndex;
        Bindgridview();
    }


In VB



Add namespace to .aspx.vb page.



Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

After write code to bind Gridview and Gridview properties as mention below:

Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If con.State = ConnectionState.Closed Then
            con.Open()
        End If
        If Not IsPostBack Then
            Bindgridview()
        End If
    End Sub
    Private Sub Bindgridview()
        Try
            Dim adp As New SqlDataAdapter("Select * from STUDENT_DETAIL", con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            If dt.Rows.Count > 0 Then
                grdstudentdetail.DataSource = dt
                grdstudentdetail.DataBind()
            Else
                dt.Rows.Add(dt.NewRow())
                grdstudentdetail.DataSource = dt
                grdstudentdetail.DataBind()
                Dim columncount As Integer = grdstudentdetail.Rows(0).Cells.Count
                grdstudentdetail.Rows(0).Cells.Clear()
                grdstudentdetail.Rows(0).Cells.Add(New TableCell())
                grdstudentdetail.Rows(0).Cells(0).ColumnSpan = columncount
                grdstudentdetail.Rows(0).Cells(0).Text = "No Records Available"
            End If
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub grdstudentdetail_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        grdstudentdetail.EditIndex = e.NewEditIndex
        Bindgridview()
    End Sub
    Protected Sub grdstudentdetail_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        Try
            Dim STUDENT_ID As Integer = Convert.ToInt32(grdstudentdetail.DataKeys(e.RowIndex).Value.ToString())
            Dim txtname As TextBox = DirectCast(grdstudentdetail.Rows(e.RowIndex).FindControl("txtname"), TextBox)
            Dim txtaddress As TextBox = DirectCast(grdstudentdetail.Rows(e.RowIndex).FindControl("txtaddress"), TextBox)
            Dim txtclass As TextBox = DirectCast(grdstudentdetail.Rows(e.RowIndex).FindControl("txtclass"), TextBox)
            Dim update As String = (("Update STUDENT_DETAIL set STUDENT_NAME ='" + txtname.Text & "', STUDENT_ADDRESS ='") + txtaddress.Text & "',STUDENT_CLASS= '") + txtclass.Text & "' where STUDENT_ID=" & STUDENT_ID
            Dim cmd As New SqlCommand(update, con)
            cmd.ExecuteNonQuery()
            grdstudentdetail.EditIndex = -1
            Response.Write("Record Update Successfully")
            Bindgridview()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub grdstudentdetail_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        grdstudentdetail.EditIndex = -1
        Bindgridview()
    End Sub
    Protected Sub grdstudentdetail_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Try
            Dim STUDENT_ID As Integer = Convert.ToInt32(grdstudentdetail.DataKeys(e.RowIndex).Value.ToString())
            Dim delete As String = "Delete from STUDENT_DETAIL where STUDENT_ID=" & STUDENT_ID
            Dim cmd As New SqlCommand(delete, con)
            cmd.ExecuteNonQuery()
            Response.Write("Record Delete Successfully")
            Bindgridview()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub grdstudentdetail_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        grdstudentdetail.PageIndex = e.NewPageIndex
        Bindgridview()
    End Sub

Now debug the application and check the result.

Related Articles on Gridview:

Ø  How to bind Gridview using Sqldataadapter, Datatable andQuery in Asp.net

Ø  How to highlight row on mouse hover in Gridview

Ø  How to edit and update Dropdownlist in Gridview datacontrol in Asp.net

Ø  How to Search Records in Gridview in Asp.net

Ø  How to Bind Gridview using Store Procedure, SqlDataAdapterand Datatable in Asp.net

Ø  How to use RadioButtonList control inside the Gridview inAsp.net

                         
  ØHow to use Fileupload control in Gridview inAsp.net

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

No comments:

Post a Comment