How to Bind, Edit, Update, Paging and Delete in FormView control in Asp.net? | ASPMANTRA | Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server AND WCF snippets and tutorial

How to Bind, Edit, Update, Paging and Delete in FormView control in Asp.net?


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

Description:
I have created a table name STUDENT_DETAIL.
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 FormView Data control from Toolbox.
<asp:FormView ID="formviewstudent" runat="server" DataKeyNames="STUDENT_ID" AllowPaging="True"
            onpageindexchanging="formviewstudent_PageIndexChanging"
            onitemupdating="formviewstudent_ItemUpdating"
            onitemdeleting="formviewstudent_ItemDeleting"
            onmodechanging="formviewstudent_ModeChanging"
           >
             <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#EFF3FB" />
        <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <ItemTemplate>
            <table style="border:1px solid #c1c1c1;">
            <tr style="background-color:#E5E5FE;font-weight:bold"><td>Student Detail</td></tr>
        
              <tr> <td><b>Student Name:-</b></td><td><asp:Label ID="lblstudentname" runat="server" Text='<%# Eval("STUDENT_NAME") %>'></asp:Label></td></tr>
              
              <tr><td><b>Student Address:-</b></td><td><asp:Label ID="lblstudentaddress" runat="server" Text='<%# Eval("STUDENT_ADDRESS") %>'></asp:Label></td></tr>
              
              <tr><td><b>Student Class:-</b></td><td><asp:Label ID="lblstudentclass" runat="server" Text='<%# Eval("STUDENT_CLASS") %>'></asp:Label></td></tr>
             <tr><td> <asp:LinkButton ID="LinkButton1" runat="server" CommandName="edit">Edit</asp:LinkButton>
                <asp:LinkButton ID="LinkButton2" runat="server" CommandName="delete">Delete</asp:LinkButton></td></tr>
                </table>
            </ItemTemplate>
            <EditItemTemplate>
            <table>
            <tr><td><b>Student Name:-</b></td><td><asp:TextBox ID="txtstudentname" runat="server" Text='<%# Eval("STUDENT_NAME") %>'></asp:TextBox></td></tr>
             <tr><td><b>Student Address:-</b></td><td><asp:TextBox ID="txtstudentaddress" runat="server" Text='<%# Eval("STUDENT_ADDRESS") %>'></asp:TextBox></td></tr>
              <tr><td><b>Student Class:-</b></td><td><asp:TextBox ID="txtstudentclass" runat="server" Text='<%# Eval("STUDENT_CLASS") %>'></asp:TextBox></td></tr>
              <tr><td><asp:LinkButton ID="lkupdate" runat="server" CommandName="update">Update</asp:LinkButton>
             
                <asp:LinkButton ID="lkcancel" runat="server" CommandName="cancel">Cancel</asp:LinkButton></td></tr>
            </table>
            </EditItemTemplate>
            <EmptyDataTemplate>
            <table style="border:1px solid #c1c1c1;">
            <tr style="background-color:#E5E5FE;font-weight:bold"><td><b>Student Details</b></td></tr>
            <tr><td><b>Student Name:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
            <tr><td><b>Student Address:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
            <tr><td><b>Student Class:-</b></td><td style="color:Red;">No Records Aviable!</td></tr>
           
            </table>
            </EmptyDataTemplate>
        </asp:FormView>
   
After that go to .aspx.cs page and add namespace.

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

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)
        {
            Bindformview();
        }
    }
    public void Bindformview()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from STUDENT_DETAIL", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                formviewstudent.DataSource = dt;
                formviewstudent.DataBind();
            }
            else
            {
                formviewstudent.DataSource = null;
                formviewstudent.DataBind();
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected void formviewstudent_PageIndexChanging(object sender, FormViewPageEventArgs e)
    {
        formviewstudent.PageIndex = e.NewPageIndex;
        Bindformview();
    }
    protected void formviewstudent_ItemUpdating(object sender, FormViewUpdateEventArgs e)
    {
        try
        {
            DataKey key = formviewstudent.DataKey;
            TextBox txtname = (TextBox)formviewstudent.FindControl("txtstudentname");
            TextBox txtaddress = (TextBox)formviewstudent.FindControl("txtstudentaddress");
            TextBox txtclass = (TextBox)formviewstudent.FindControl("txtstudentclass");
            string Update = "Update STUDENT_DETAIL set STUDENT_NAME='" + txtname.Text.ToString() + "',STUDENT_ADDRESS='" + txtaddress.Text.ToString() + "',STUDENT_CLASS='" + txtclass.Text.ToString() + "' where STUDENT_ID=" + key.Value.ToString();
            SqlCommand cmd = new SqlCommand(Update, con);
            cmd.ExecuteNonQuery();
            Messagebox("Record Update Successfully");
            formviewstudent.ChangeMode(FormViewMode.ReadOnly);
            Bindformview();
        }
        catch (Exception ex)
        {
        }
    }
    protected void formviewstudent_ModeChanging(object sender, FormViewModeEventArgs e)
    {
        formviewstudent.ChangeMode(e.NewMode);
        Bindformview();
      
    }
    protected void formviewstudent_ItemDeleting(object sender, FormViewDeleteEventArgs e)
    {
        try
        {
          
            DataKey key = formviewstudent.DataKey;
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "delete from STUDENT_DETAIL where STUDENT_ID='" + key.Value.ToString() + "'";
                  cmd.ExecuteNonQuery();
            Messagebox("Delete Record Successfully");
            formviewstudent.ChangeMode(FormViewMode.ReadOnly);
            Bindformview();

        }
        catch (Exception ex)
        {
        }
    }
    //To show message
    private void Messagebox(string Message)
    {
        Label lblMessageBox = new Label();

        lblMessageBox.Text =
            "<script language='javascript'>" + Environment.NewLine +
            "window.alert('" + Message + "')</script>";

        Page.Controls.Add(lblMessageBox);

    }


In VB:
Go to .aspx.vb page and add namespace.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

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
            Bindformview()
        End If
    End Sub
    Public Sub Bindformview()
        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
                formviewstudent.DataSource = dt
                formviewstudent.DataBind()
            Else
                formviewstudent.DataSource = Nothing
                formviewstudent.DataBind()
            End If
        Catch ex As Exception
        End Try
    End Sub

    Protected Sub formviewstudent_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewPageEventArgs) Handles formviewstudent.PageIndexChanging
        formviewstudent.PageIndex = e.NewPageIndex
        Bindformview()
    End Sub
    Protected Sub formviewstudent_ItemUpdating(ByVal sender As Object, ByVal e As FormViewUpdateEventArgs)
        Try
            Dim key As DataKey = formviewstudent.DataKey
            Dim txtname As TextBox = DirectCast(formviewstudent.FindControl("txtstudentname"), TextBox)
            Dim txtaddress As TextBox = DirectCast(formviewstudent.FindControl("txtstudentaddress"), TextBox)
            Dim txtclass As TextBox = DirectCast(formviewstudent.FindControl("txtstudentclass"), TextBox)
            Dim Update As String = "Update STUDENT_DETAIL set STUDENT_NAME='" & txtname.Text.ToString() & "',STUDENT_ADDRESS='" & txtaddress.Text.ToString() & "',STUDENT_CLASS='" & txtclass.Text.ToString() & "' where STUDENT_ID=" & key.Value.ToString()
            Dim cmd As New SqlCommand(Update, con)
            cmd.ExecuteNonQuery()
            Messagebox("Record Update Successfully")
            formviewstudent.ChangeMode(FormViewMode.[ReadOnly])
            Bindformview()
        Catch ex As Exception
        End Try
    End Sub
    Protected Sub formviewstudent_ModeChanging(ByVal sender As Object, ByVal e As FormViewModeEventArgs)
        formviewstudent.ChangeMode(e.NewMode)
        Bindformview()

    End Sub
    Protected Sub formviewstudent_ItemDeleting(ByVal sender As Object, ByVal e As FormViewDeleteEventArgs)
        Try

            Dim key As DataKey = formviewstudent.DataKey
            Dim cmd As New SqlCommand()
            cmd.Connection = con
            cmd.CommandText = "delete from STUDENT_DETAIL where STUDENT_ID='" & key.Value.ToString() & "'"
                     cmd.ExecuteNonQuery()
            Messagebox("Delete Record Successfully")
            formviewstudent.ChangeMode(FormViewMode.[ReadOnly])

            Bindformview()
        Catch ex As Exception
        End Try
    End Sub
    'To show message
    Private Sub Messagebox(ByVal Message As String)
        Dim lblMessageBox As New Label()

        lblMessageBox.Text = "<script language='javascript'>" + Environment.NewLine & "window.alert('" & Message & "')</script>"

        Page.Controls.Add(lblMessageBox)

    End Sub
Now debug the project and check the result.


Related Articles on Formview:

Ø   How to Bind Formview Data control in Asp.netusing Store Procedure?

Ø  How to Bind Formview control using Sqldataadapter,Datatable and Query in Asp.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.

Post a Comment

[blogger]

MKRdezign

Contact Form

Name

Email *

Message *

Powered by Blogger.
Javascript DisablePlease Enable Javascript To See All Widget