Home > DeveloperSection > Articles > FormView Control in ASP.Net

FormView Control in ASP.Net


ADO.Net ADO.Net 
Ratings:
1 Comment(s)
 13218  View(s)
Rate this:

FormView Control in ASP.Net

The FormView control is used to display a single record from a data source. It is similar to the DetailsView control, except it displays user-defined templates instead of row fields. Creating your own templates gives you greater flexibility in controlling how the data is displayed. The FormView control supports the following features:

·         Binding to data source controls, such as SqlDataSource and ObjectDataSource.

·         Built-in inserting capabilities.

·         Built-in updating and deleting capabilities.

·         Built-in paging capabilities.

<asp:FormView ID="FormView1" runat="server">

</asp:FormView>

FormView Control in ASP.Net

 

<asp:FormView ID="FormView1" runat="server" AllowPaging="True" EnableModelValidation="True"OnItemDeleting="FormView1_ItemDeleting" OnItemUpdating="FormView1_ItemUpdating"OnModeChanging="FormView1_ModeChanging" OnPageIndexChanging="FormView1_PageIndexChanging"

BorderStyle="Double" BorderWidth="1px" HorizontalAlign="Left" OnItemCommand="FormView1_ItemCommand">

<ItemTemplate>

   <table border="2">

      <tr>

         <td>

         </td>

         <td>

  ID &nbsp;&nbsp;<asp:Label ID="lbl1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"id") %>'></asp:Label>

          </td>

          <td>

 Password &nbsp;&nbsp;<asp:Label ID="Label1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"pass") %>'></asp:Label>

           </td>

           <td>

 NAME&nbsp;&nbsp;<asp:Label ID="Label2" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"name") %>'></asp:Label>

           </td>

           <td>

<asp:LinkButton ID="lnkbtn1" runat="server" CommandName="edit">edit</asp:LinkButton>

           </td>

           <td>

<asp:LinkButton ID="LinkButton3" runat="server" CommandName="delete">delete</asp:LinkButton>

           </td>

       </tr>

   </table>

</ItemTemplate>

 

<EditItemTemplate>

            <asp:TextBox ID="txt1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"id") %>'></asp:TextBox>

            <asp:TextBox ID="TextBox1" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"pass") %>'></asp:TextBox>

            <asp:TextBox ID="TextBox2" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"name") %>'></asp:TextBox>

            <asp:LinkButton ID="lnkbtn2" runat="server" CommandName="update">update</asp:LinkButton>

            <asp:LinkButton ID="LinkButton1" runat="server" CommandName="cancel">cancel</asp:LinkButton>

            <asp:Label ID="lbl2" runat="server"></asp:Label>

        </EditItemTemplate>

 

 <FooterTemplate>

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

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

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

            <asp:LinkButton ID="LinkButton2" runat="server" CommandName="ADD">ADD</asp:LinkButton>

 </FooterTemplate>

 </asp:FormView>

DataBinder.Eval takes the argument. The first arg is the data object to bind to. The second arg is the string name of the field which will display on the page.

BindData:

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

Binddata();// this function is called when the page is loaded.

 

}

}

   

public void Binddata()

{

DataSet ds = new DataSet();

       

// Here data is fetched from the database through stored procedure(insert_reg)

FormView1.DataSource = Class1. execute_spfill_grid ("insert_reg");

FormView1.DataBind();

}

In above code execute_spfill_grid is a function created in Class1.cs which is described below.

And insert_reg is a stored procedure made in backend.This is described below

The FormView control raises the PageIndexChanging event when a pager button (a button with its CommandName property set to "Page") within the control is clicked. But before the DetailsView control handles the paging operation. This allows you to provide an event handler for paging operation.

 

protected void FormView1_PageIndexChanging(object sender, FormViewPageEventArgs e)

{

FormView1.PageIndex = e.NewPageIndex;

Binddata();       

}

FormView Control in ASP.Net

FormView Control in ASP.Net

EditMode:

FormView has ModeChanging event by which you can change normal mode to edit mode .In ths event we can also cancel edit mode.

protected void FormView1_ModeChanging(object sender, FormViewModeEventArgs e)

{

FormView1.ChangeMode(FormViewMode.Edit);

Binddata();

        

if (e.CancelingEdit == true)

{

Response.Redirect("Default.aspx");

}

}

FormView Control in ASP.Net

FormView Control in ASP.Net

ADD, UPDATE and Delete in FormView:

ItemCommand event is used for programmatically determining which specific command button is clicked and take appropriate action. Here this event is used for Adding data

protected void FormView1_ItemCommand(object sender,FormViewCommandEventArgse)

{

if (e.CommandName == "ADD")

{

// Here  FindControl will find the TextboxId in which adding will be done.

 

            TextBox l = FormView1.FindControl("TextBox3") as TextBox;

            string i = l.Text;

            TextBox a = FormView1.FindControl("TextBox4") as TextBox;

            string p = a.Text;

            TextBox b = FormView1.FindControl("TextBox5") as TextBox;

            string m = b.Text;

 

            Class1.updat_reg("add_reg", i, p, m);

            Response.Redirect("Default.aspx");

Binddata();

}

}

 

ItemUpdating event is used to update data

 

protected void FormView1_ItemUpdating(object sender,FormViewUpdateEventArgse)

{

// Here  FindControl will find the TextboxId in which updating will be done.

 

TextBox l = FormView1.FindControl("txt1") as TextBox;

string i = l.Text;

TextBox a = FormView1.FindControl("TextBox1") as TextBox;

string p = a.Text;

TextBox b = FormView1.FindControl("TextBox2") as TextBox;

string m = b.Text;

 

Class1.updat_reg("update_reg", i, p, m);

Response.Redirect("Default.aspx");

Binddata();

}

 

ItemDeleting event is used to delete data.

 

protected void FormView1_ItemDeleting(object sender,FormViewDeleteEventArgse)

{

Label l = FormView1.FindControl("lbl1") as Label;

string i = l.Text;

Class1.delete_reg("del_reg", i);

Binddata();

}

 

FormView Control in ASP.Net

 

FormView Control in ASP.Net

 

 

Add both namespace in every .cs page in which you want to use data and SQL related keyword

using System.Data;

using System.Data.SqlClient;

Class1.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Data;

using System.Data.SqlClient;

using System.Web;

 

public class Class1

{

 

    // this function is used to bind data

    public static DataSet execute_spfill_grid(string spname)

    {

 

        SqlConnection con = Connection.CreateConnection();

 

        DataSet ds = new DataSet();

 

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = spname;

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Connection = con;

        con.Open();

        SqlDataAdapter da = new SqlDataAdapter(spname,con);

        da.Fill(ds);

    

        return ds;

      

    }

 

 

    public static void update_reg_form(string spname, string id, string pass, string name) // this function is used to update data

    {

        SqlConnection con = Connection.CreateConnection();

       

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = spname;

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;

        cmd.Parameters.Add("@pass", SqlDbType.VarChar).Value = pass;

        cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;

 

        cmd.Connection = con;

        con.Open();

       

        cmd.ExecuteNonQuery();

        con.Close();

    }

 

    public static void ADD_reg_form(string spname, string id, string pass, string name)// this function is used to Add data

    {

        SqlConnection con = Connection.CreateConnection();

 

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = spname;

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;

        cmd.Parameters.Add("@pass", SqlDbType.VarChar).Value = pass;

        cmd.Parameters.Add("@name", SqlDbType.VarChar).Value = name;

 

        cmd.Connection = con;

        con.Open();

 

        cmd.ExecuteNonQuery();

        con.Close();

    }

 

 

 

    public static void DEL_reg_form(string spname, string id)// this function is used to Delete data

    {

        SqlConnection con = Connection.CreateConnection();

        SqlCommand cmd = new SqlCommand();

        cmd.CommandText = spname;

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = id;      

        cmd.Connection = con;

        con.Open();

        cmd.ExecuteNonQuery();

        con.Close();

    }

}

 

In class1.cs  Connection keyword is used . Connection is a class in whichCreateConnection function is created.

Connection.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Configuration;

using System.Web;

using System.Data;

using System.Data.SqlClient;

 

public class Connection

{

 

    public static SqlConnection CreateConnection()

    {

        string connectionstring;

        connectionstring = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;

        SqlConnection sqlcon = new SqlConnection(connectionstring);

        return sqlcon;

    }

   

}

 

mycon is connection object created in web.config

web.config:

<connectionStrings>

            <add name="mycon"connectionString="Data Source=(local);Initial Catalog=my; User Id=sa; Password=mindstick"providerName="System.Data.SqlClient"/>

      </connectionStrings>

Write this connection string above <system.web>

Stored procedure:

 

This procedure is used to select data

Create procedure insert_reg

 

as

begin

select * from regform

end

This procedure is used to Add data

Create procedure add_reg

@id varchar(50),

@pass varchar(50),

@name varchar(50)

as

begin

insert into regform

(id,pass,name

)

values

(

@id,

@pass,

@name

)

End

This procedure is used to Delete data

create procedure del_reg

@id varchar(50)

as

begin

delete  from regform where id=@id

end

This procedure is used to Update data

create procedure [dbo].[update_reg]

@id varchar(50),

@pass varchar(50),

@name varchar(50)

as

begin

update regform set pass=@pass,name=@name where id=@id

end


Good explaination

By Mohib Suleman on   2 years ago
Thanks for the explaination.
Could you please explain the same with a MS Access database.
My email id is ridahmohib@gmail.com

Thanks and Regards,

Don't want to miss updates? Please click the below button!

Follow MindStick