How to use ADO.Net with Formview control?

 Hi everyone.

  I am using ADO.Net(code) to Insert,update,delete,select record into the database.

  i have a user input form and formview in my project. 

  When i enter user info and click insert button the data in the input form gets saved in the database as well as the form gets redireted to

  formview.aspx.

  But i m not able to extract the values from the database and show it in the formview.

  i know i can do this using SqlDataSource.

 But i want to use code to bind the record to the formview instead of using sqldatasource or objectdatasource.

any suggestion what changes do i need to make in the code to accomplish this task?

Thanks.

 jack.
 

  

0
jack007
4/4/2008 7:08:14 AM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

9 Replies
909 Views

Similar Articles

[PageSpeed] 0

Here's an example of CRUD with a FormView and ADO.Net:

ASPX 

<%@ page autoeventwireup="true" codefile="CRUDWithADO.aspx.cs" inherits="FormView_CRUDWithADO"
	language="C#" masterpagefile="~/MasterPages/Default.master" title="FormView: CRUD With ADO" %>

<asp:content id="Content1" runat="Server" contentplaceholderid="ContentPlaceHolder1">
	<asp:label id="lblMessage" runat="server" enableviewstate="false" />
	<asp:formview id="fvShipper" runat="server" allowpaging="True" datakeynames="ShipperID"
		onitemdeleting="fvShipper_ItemDeleting" oniteminserting="fvShipper_ItemInserting"
		onitemupdating="fvShipper_ItemUpdating" onmodechanging="fvShipper_ModeChanging"
		onpageindexchanging="fvShipper_PageIndexChanging" style="margin-top: 20px;">
		<edititemtemplate>
			ShipperID:
			<asp:label id="lblShipperID" runat="server" text='<%# Eval("ShipperID") %>' /><br />
			CompanyName:
			<asp:textbox id="txtCompanyName" runat="server" text='<%# Bind("CompanyName") %>' /><br />
			Phone:
			<asp:textbox id="txtPhone" runat="server" text='<%# Bind("Phone") %>' /><br />
			<asp:linkbutton id="btnUpdate" runat="server" causesvalidation="True" commandname="Update"
				text="Update" />
			<asp:linkbutton id="btnCancel" runat="server" causesvalidation="False" commandname="Cancel"
				text="Cancel" />
		</edititemtemplate>
		<insertitemtemplate>
			CompanyName:
			<asp:textbox id="txtCompanyName" runat="server" text='<%# Bind("CompanyName") %>' /><br />
			Phone:
			<asp:textbox id="txtPhone" runat="server" text='<%# Bind("Phone") %>' /><br />
			<asp:linkbutton id="btnInsert" runat="server" causesvalidation="True" commandname="Insert"
				text="Insert" />
			<asp:linkbutton id="btnCancel" runat="server" causesvalidation="False" commandname="Cancel"
				text="Cancel" />
		</insertitemtemplate>
		<itemtemplate>
			ShipperID:
			<asp:label id="lblShipperID" runat="server" text='<%# Eval("ShipperID") %>' /><br />
			CompanyName:
			<asp:label id="lblCompanyName" runat="server" text='<%# Bind("CompanyName") %>' /><br />
			Phone:
			<asp:label id="lblPhone" runat="server" text='<%# Bind("Phone") %>' /><br />
			<asp:linkbutton id="EditButton" runat="server" causesvalidation="False" commandname="Edit"
				text="Edit" />
			<asp:linkbutton id="btnDelete" runat="server" causesvalidation="False" commandname="Delete"
				text="Delete" />
			<asp:linkbutton id="btnNew" runat="server" causesvalidation="False" commandname="New"
				text="New" />
		</itemtemplate>
	</asp:formview>
</asp:content>

CODE-BEHIND 

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class FormView_CRUDWithADO : System.Web.UI.Page
{
	private void SetData()
	{
		SqlConnection conn = new SqlConnection(
			ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
		SqlCommand cmd = new SqlCommand("SELECT * FROM [Shippers]", conn);
		SqlDataAdapter adapter = new SqlDataAdapter(cmd);

		try
		{
			conn.Open();
			DataSet ds = new DataSet();
			adapter.Fill(ds);

			fvShipper.DataSource = ds;
			fvShipper.DataBind();
		}
		finally
		{
			if (conn != null) { conn.Close(); }
		}
	}
	
	protected void Page_Load(object sender, EventArgs e)
    {
		if (!this.IsPostBack)
		{
			this.SetData();
		}
    }

	protected void fvShipper_ModeChanging(object sender, FormViewModeEventArgs e)
	{
		fvShipper.ChangeMode(e.NewMode);
		this.SetData();
	}

	protected void fvShipper_PageIndexChanging(object sender, FormViewPageEventArgs e)
	{
		fvShipper.PageIndex = e.NewPageIndex;
		this.SetData();
	}

	protected void fvShipper_ItemInserting(object sender, FormViewInsertEventArgs e)
	{
		TextBox txtCompanyName = fvShipper.FindControl("txtCompanyName") as TextBox;
		TextBox txtPhone = fvShipper.FindControl("txtPhone") as TextBox;

		if (txtCompanyName == null) { return; }
		if (txtPhone == null) { return; }

		SqlConnection conn = new SqlConnection(
			ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
		SqlCommand cmd = new SqlCommand(
			"INSERT INTO [Shippers] ([CompanyName], [Phone]) VALUES (@CompanyName, @Phone); SELECT @ShipperID = SCOPE_IDENTITY()", 
			conn);
		cmd.Parameters.AddWithValue("CompanyName", txtCompanyName.Text);
		cmd.Parameters.AddWithValue("Phone", txtPhone.Text);
		cmd.Parameters.Add("ShipperID", SqlDbType.Int);
		cmd.Parameters["ShipperID"].Direction = ParameterDirection.Output;

		try
		{
			conn.Open();

			if (cmd.ExecuteNonQuery().Equals(1))
			{
				lblMessage.Text = String.Format(
					"Shipper '{0}' successfully added.", 
					cmd.Parameters["ShipperID"].Value);

				fvShipper.ChangeMode(FormViewMode.ReadOnly);

				this.SetData();
			}
		}
		finally
		{
			if (conn != null) { conn.Close(); }
		}
	}

	protected void fvShipper_ItemUpdating(object sender, FormViewUpdateEventArgs e)
	{
		TextBox txtCompanyName = fvShipper.FindControl("txtCompanyName") as TextBox;
		TextBox txtPhone = fvShipper.FindControl("txtPhone") as TextBox;

		if (txtCompanyName == null) { return; }
		if (txtPhone == null) { return; }

		SqlConnection conn = new SqlConnection(
			ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
		SqlCommand cmd = new SqlCommand(
			"UPDATE [Shippers] SET [CompanyName] = @CompanyName, [Phone] = @Phone WHERE (ShipperID = @ShipperID)",
			conn);
		cmd.Parameters.AddWithValue("ShipperID", fvShipper.DataKey["ShipperID"]);
		cmd.Parameters.AddWithValue("CompanyName", txtCompanyName.Text);
		cmd.Parameters.AddWithValue("Phone", txtPhone.Text);

		try
		{
			conn.Open();

			if (cmd.ExecuteNonQuery().Equals(1))
			{
				lblMessage.Text = String.Format(
					"Shipper '{0}' successfully updated.",
					cmd.Parameters["ShipperID"].Value);

				fvShipper.ChangeMode(FormViewMode.ReadOnly);

				this.SetData();
			}
		}
		finally
		{
			if (conn != null) { conn.Close(); }
		}
	}

	protected void fvShipper_ItemDeleting(object sender, FormViewDeleteEventArgs e)
	{
		SqlConnection conn = new SqlConnection(
			ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
		SqlCommand cmd = new SqlCommand(
			"DELETE FROM [Shippers] WHERE (ShipperID = @ShipperID)",
			conn);
		cmd.Parameters.AddWithValue("ShipperID", fvShipper.DataKey["ShipperID"]);

		try
		{
			conn.Open();

			if (cmd.ExecuteNonQuery().Equals(1))
			{
				lblMessage.Text = String.Format(
					"Shipper '{0}' successfully deleted.",
					cmd.Parameters["ShipperID"].Value);

				fvShipper.ChangeMode(FormViewMode.ReadOnly);

				this.SetData();
			}
		}
		finally
		{
			if (conn != null) { conn.Close(); }
		}
	}
}

Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
4/4/2008 1:12:03 PM

Hi ecbruck,

Thanks for the reply.

But i got bit confused here.

Cant i use formview just like detialsview? 

while binding the database row to the detailsview,

i could have just written following lines of code:-

        //SqlConnection
        string str = "select * from customer";
        SqlDataAdapter oda = new SqlDataAdapter(str, conn);
        conn.Open();
        DataSet ods = new DataSet();
        oda.Fill(ods, "info");
        DetailsView1.DataSource = ods.Tables["info"].DefaultView;
        DetailsView1.DataBind();

        conn.Close();

 but here in form view do i need to write following lines of code evertime manually:-

 

text='<%# Eval("ShipperID") %>'
 text='<%# Bind("Phone") %>' 
text='<%# Bind("Phone") %>' 
text='<%# Bind("CompanyName") %>' 
I hope your getting it.
Thanks.
Jack. 
 
0
jack007
4/6/2008 5:32:12 AM

Hi jack007 ,

jack007:
        //SqlConnection
        string str = "select * from customer";
        SqlDataAdapter oda = new SqlDataAdapter(str, conn);
        conn.Open();
        DataSet ods = new DataSet();
        oda.Fill(ods, "info");
        DetailsView1.DataSource = ods.Tables["info"].DefaultView;
        DetailsView1.DataBind();

        conn.Close();

In this senario, DetailsView control auto generate all fields.

jack007:
text='<%# Eval("ShipperID") %>'
 text='<%# Bind("Phone") %>' 
text='<%# Bind("Phone") %>' 
text='<%# Bind("CompanyName") %>' 

But in this senario, you bind fields maually. This way is flexible.

 



Samu Zhang
Microsoft Online Community Support

Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question.
0
Samu
4/7/2008 3:27:23 AM

jack007:

Hi ecbruck,

Thanks for the reply.

But i got bit confused here.

Cant i use formview just like detialsview? 

while binding the database row to the detailsview,

i could have just written following lines of code:-

        //SqlConnection
        string str = "select * from customer";
        SqlDataAdapter oda = new SqlDataAdapter(str, conn);
        conn.Open();
        DataSet ods = new DataSet();
        oda.Fill(ods, "info");
        DetailsView1.DataSource = ods.Tables["info"].DefaultView;
        DetailsView1.DataBind();

        conn.Close();

 but here in form view do i need to write following lines of code evertime manually:-

 

text='<%# Eval("ShipperID") %>'
 text='<%# Bind("Phone") %>' 
text='<%# Bind("Phone") %>' 
text='<%# Bind("CompanyName") %>' 
I hope your getting it.
Thanks.
Jack. 

The FormView does not have BoundColumns as a DetailsViev does. Therefore, you need to template the control exactly as you want, leaving the binding of the inner controls up to you.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
4/7/2008 12:22:33 PM

 Hi Everyone  

 Thanks for the reply.

 Ok i got it.

 So does that mean i have manually bind each control and manually write this line of code :-

text='<%# Eval("ShipperID") %>'
 text='<%# Bind("Phone") %>' 
text='<%# Bind("Phone") %>' 
text='<%# Bind("CompanyName") %>'
Or can this be achieved using wizard instead? without needing to write all the code manually.
Thanks.
Jack.  

 

  

 

  

0
jack007
4/8/2008 5:43:17 AM

  Hi,

 Thanks.

 But i have few doubts:-  

 1.how do i bind the listbox and dropdownlist within formview?

 2.can i use ajax and javascript inside formview?

 Thanks.

 Jack. 

 

 

0
jack007
4/11/2008 5:50:22 AM

  Hi ecbruck,

 Thanks for the code.

  It worked.

 For textbox we wrote these codes inside formview.cs:-

 TextBox txtPhone = fvShipper.FindControl("txtPhone") as TextBox;
 cmd.Parameters.AddWithValue("Phone", txtPhone.Text);

 But, What code should i write if there is lisbox,dropdownlist or radiobuttons?

 Secondly, i am able to display the paging as NEXT and PREVIOUS using the pagersettings.
 But is there someway i could replace those links with the asp button server controls? 
 Any further suggestion/codes?
 Thanks.
 Jack. 

 

 

 

 


0
jack007
4/29/2008 7:39:02 AM

Any control embedded within a FormView template can be extracted the same way using the FindControl method. Just make sure to cast your returned object to its correct state. As far as paging goes, you can specify a PagerTemplate and make it as you want. If you have further questions regarding these subjects, please post a new question to the group.


Thanks, Ed

Microsoft MVP - ASP/ASP.NET

0
ecbruck
4/29/2008 12:04:17 PM

 Hi,

 In the above example i want to add listbox and dropdownlist inside formview .

 and do view,update,insert,delete record as above. 

  Ok i added these lines to find dropdownlist and listbox inside formview :-

 DropDownList DropDownList1 = FormView1.FindControl("DropDownList1") as DropDownList;

 ListBox ListBox1 = FormView1.FindControl("ListBox1") as ListBox; 

 but i didnt use any <# bind> expression in the source code. 

 But how do i display the data inside those controls and how to do update and insert on them using code behind?

 i hope ur getting it.

 could you modify the above code? 

 Here is the new link.you can reply back in the below link:-

 http://forums.asp.net/t/1254792.aspx

Thanks.

 jack. 

 

 

0
jack007
4/30/2008 9:01:29 AM
Reply:

Similar Artilces:

using a .Net Control as activex control in VCL form
Hi , We have a to integrate a simple .Dot CSharp control which needs to be integrated into bcb2010 VCL form as a control. We will place the control on the VCL form along with other VCL controls's. I tried creating a simple .net control using a lable+textbox and trying to use in vcl form. I have made the assembly comvisible and generated tlb files and .bpl for the component. I could see the component in "ActiveX" tool palette. But when I drag the object onto VCL form and try to access its attributes I run into problems. I am not able to see .net control on the vcl at runti...

ajax.net controls used in custom composite controls?
I am creating an events calendar that uses the accordion to display the events for the selected day.  The problem I'm having is that the accordion is not responding to any client side events.  I would really like to find a good "How to" article for building composite controls that incorporate an ajax.net control like the accordion....

Issue using control created in VS.net 2003 in VS.net 2002
I have a friend that has an issue using my asp.net C# custom control in Visual Studio.net 2002 that I have compiled under Visual Studio.net 2003. I never did test it with that version, but I was under the impression that it should still work as long as you don't use any features specific to the 1.1 framework (which I really don't think I did). My guess now is that this is correct, but only when using 2002 controls in 2003. I have searched the web, these forums, and MSDN for the last 30 minutes with no real answer. The guy that runs MetaBuilders (http://www.metabuilders.com/Faq.aspx) tell...

How do the different data presentation controls equate in ADO.net?
How does Visual Studio create ado.net equivalents of the datagrid's and gridview's columns and rows?  I am assuming they make a DataRow for each of the rows.  Am I on the right track with this?Is the table created by gridview basically a dataset from ADO.net?  Can anyone offer any guidance with this?Thanks to everyone that has ever helped me with any posts. Hi newbie2C#, The row in datagrid is called DataGridItem and in gridview is called GridViewRow. They are all inherits TableRow Class. DataRow is only one kind of row in GridView control. There are many other t...

populate Grid view control through programming using Ado.net
i am working in visual studio 2005 .i want to populate Grid view control  through programming using Ado.net  with result of datareader ,gridview is already filled with a datasource control but there is an error " Index is out of Rang And Index cant negative" plz any one help me Code is : GrdManageMessages.DataSourceID = ""GrdManageMessages.DataBind()  Dim i As Integer = 0Dim SqlConnect As SqlConnection = New SqlConnection("Data Source=COMMANDER\SQLEXPRESS;Initial Catalog=Enotice;Integrated Security=True")      &n...

How to perform Ado.net with Formview and bind different types of controls with it?
Hi,I ve started using formview recently n came up with lots of confusion.Here are Few question regarding formview. I m able to put the textbox,buttons,labels etc inside itemtemplate of the formview. I also used <%# Bind> expression to bind the controls to the database fields and show the data into the webform.I m using ado.net(C#) till here.now;1.How to do insert,edit and delete query similarly from code behind?i know i have to use edit template,insertitemtemplate.But how to do using code? 2.Do i need to use something like 'findcontrol as textbox' for other controls ...

What control do I use (or do I not use a control at all...)
Okay so here's the story so far. I am making a blog to be incorporated into a website. Well, I'm doing the blog from scratch. I'm using MySQL to source all the data via MySQL .NET/Connector. Now while developing the script, I used DataReader and Response.Write to show the blog topics. Now that it has come to put it under a design (I'm using a Master Page for that), I've hit the problem. Response.Write shows all the topics before any of the design elements could be incorporated. So that (more or less) is out of question. So next I looked into the data presentation controls. I looked up GridVi...

Sending SMS using vb.net or C#.net using vb.net or c#.net
Hi  My requirement is I hav one csv file with these fields id,mobilenum,messgae,status.intiallu staus is 0. once i read the all fileds and take that mobile number.using tat mobile number  i need to send sms .after sending sms i shuld change status as 1 How to send sms thru coding (please dont provide any links.if it is provide also please give working links becox i checked codeproject .i didnt get any nice link. and also provide the how to update the status field im csv file   Thank ssandhya   To send SMS, you need some third party SMS providers. if you consul...

Using ADO.NET instead of the DataSource controls in Visual studio 2005
I am using VS 2005 and SQL server 2005. We will have several web forms which are populated with data from our database. The web forms have various controls that will be bound to the data which is extracted from the database. For example, a drop down list box, etc. I have noticed that in ASP.NET 2.0 that they have several built in Data Source controls. For example, SqlDataSource control, ObjectDataSource control, XmlDataSource control, SiteMapDataSource control. I have looked at these controls but I don't like the fact that things are wired up automoatically through the Visual Studio wizard....

Datagrid(.net 1.1) to GridView(.net 2.0) and using the RowUpdating event how to extract the values from the controls.
Ok  This is the settings: I use a Viewgrid with only itemtemplate colums for example. <asp:TemplateField HeaderText="Test"><ItemTemplate><asp:Label id="LBL_Test" text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' runat="server" meta:resourcekey="LBL_TestResource1"></asp:Label></font></ItemTemplate> <EditItemTemplate><asp:TextBox ID="HDN_Test" Text='<%# DataBinder.Eval(Container.DataItem, "Test1") %>' Runat="server" meta:resourcekey="HDN_TestResource1" /></EditItemTemplate></asp:TemplateField>  The ...

Using Validation controls with FormView control
Hello dears; Is  it possible to use validation controls with FormView or DetailsView controls during Edit mode? Such controls have no Error Events handlers to use and there textboxes have only TextChanged Event handlers which have no text property. Also how can i get the content of a cell in theFormView ? Thanks alot  VWD2005 The FormView control supports templates -- so you could add an ItemTemplate or EditTemplate to it, and absolutely put validation controls within there as well. Hope this helps, Scott Thanks Scott  VWD2005 Hello I know your busy but I can'...

Trouble controlling .net controlls with CSS
 I am trying to control the :hover css property on <asp: Button> controls. Basically the css is working correctly to set the initial look of the button, but nothing is happening when I hover over the button. Here is my code:CSS:.sidebarButton{    width: 168px;     height: 45px;     background-color: #666666;     text-align: left;    font-weight: bold;    font-family: Century Gothic;    font-size: 13pt;    color: White;    border-style: none;  ...

how can we achieve concurrency control in ADO.Net using DataSet ? some samples please ...,,
In dataset I am having 'employee' table, 3 users are accessing the employee table at the  same time. One is updating first row in table..... and 2'nd one is deleting the same data....  3'rd person is updating the first row in table ........  how can we overcome these type of problems ? Use transactions, here is an article that explains it: http://www.code-magazine.com/article.aspx?quickid=0605031Good Luck and happy programming!Let's build community! If my post helped you, mark it as the Answer and I will do the same when you help me...this will help eve...

how to use validation controls on FormView control?
Hi all,  I searched the forum for a solution to my problem, but while many of you seem to have had similar problems, I couldn't solve my (I thought easy) problem. This is my setup: I try to put a FormView control on my page where users can insert records into a database. All good, except that I want to add some Validation controls to my form, at least some RequiredField validators. I tried adding the controls in the InsertItem Template for starters, but that doesn't seem to work:" Unable to find control id 'FirstNameTextBox' referenced by the 'ControlT...

Web resources about - How to use ADO.Net with Formview control? - asp.net.presentation-controls

Visual Studio 2008 and .NET Framework 3.5 Service Pack 1 Beta
In this article, Scott discusses the recently released beta version of Visual Studio 2008 and .NET Framework 3.5 Service Pack 1. He starts with ...

Visual Studio 11 Beta in Context
... data controls. I blogged about this before in my Elegant Web Forms post . There's two way data-binding in controls like the FormView now instead ...

Visual Studio General Questions Forum
Sign in Home Samples Languages Extensions Documentation Community Forums CodePlex User Voice File a Bug Get started for free Visual Studio Developer ...

Advanced Residential Search
HOME MEMBERS WHAT IS WERS LINKS NEWS CONTACT US CERTIFIED PRODUCTS HUB Search Members Members Info Members Area WERS Simulators About WERS FAQs ...

Delicious
Keep, share, and discover the best of the Web using Delicious, the world's leading social bookmarking service.

ASP.NET Web Forms DynamicData FieldTemplates for DbGeography Spatial Types
... - 10 Tutorials Mixing Razor Views and WebForms Master Pages with ASP.NET MVC DbGeography FieldTemplates for ASP.NET Web Forms Here's a FormView ...

Resources last updated: 12/19/2015 11:11:57 PM