ASP .NET Tutorial
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
The Label web server control is one of the simplest control. The output of label web server control is the HTML <span> tag. In this discussion we will see the following aspects.
In the following example the usage of label web server control is explained. The property "Text" is used to assign a value (label) to the label control.
| <html> <head> <title>Label Web Server Control</title> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Label Server Control</h3> <form ID="Form1" runat=server> <asp:label id="label1" Text="This is my FIRST ASP.NET Page!" runat="server" /> </form> </body> </html> |
In our next example, we can observe that, we assign the text dynamically to the label control. In the page load event, the value "This is my FIRST ASP.NET Page!" is assigned to the property text.
| <html> <head> <title>Label Web Server Control</title> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs) Label1.text = "This is my FIRST ASP.NET Page!" End Sub </script> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Label Server Control</h3> <form ID="Form2" runat=server> <asp:label id="label1" runat="server" /> </form> </body> </html> |
In our final example, we will see how can we make use of other properties of the label control. The properties which is shown in the following example include tooltip, borderwidth, bordercolor, backcolor and forecolor. The property, borderwidth expects a unit. That is why we have declared a variable called "bdw", which is of type unit. And to assign colors for border, background and foreground, we use the Color object. By default, the color object is not available, since we import the namespace, "system.drawing".
| <%@ Import Namespace="system.drawing"%> <html> <head> <title>Label Web Server Control</title> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs) Dim bdw as unit Label1.tooltip="This is my FIRST ASP.NET page!" Label1.BorderWidth=bdw.pixel(1) Label1.text = "This is my FIRST ASP.NET page!" Label1.bordercolor = Color.Black Label1.backcolor = Color.Red Label1.forecolor = Color.White End Sub </script> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Label Server Control</h3> <form ID="Form1" runat=server> <asp:label id="label1" runat="server" /> </form> </body> </html> |
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
We can get inputs from user in variety of ways. One of the way is through textbox. In this session, we will see how to ..
In the following example the usage of label web server control is explained. The property "Text" is used to assign a value (label) to the label control. We also have a button control which is used to submit the value back to the page.
| <html> <head> <title>Textbox Web Server Control - by Das <script language="VB" runat="server"> Sub MySub(sender As Object, e As EventArgs) lblMsg.text = "Is Your First Name, " & txtFname.text & " ?" End Sub </script> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Textbox Server Control</h3> <form ID="Form1" runat=server> First Name <asp:TextBox id=txtFname Runat=server /> <asp:Button Text="Submit" OnClick="MySub" Runat=server /> <asp:Label id=lblMsg ForeColor="#ff0000" Runat=server /> </form> </body> </html> |
If we have web application, then we will definitely have a Login module. For any login password is a must. In ASP .NET we have to make use of the property, textmode=password. We can access the password value by saying, txtPwd.Text, were txtPwd is a textbox of type password. It should be also noted that, to concatinate a string, we can use the operator += just as in C/C++.
| <html> <head> <title>Textbox Web Server Control - by Das</title> <script language="VB" runat="server"> Sub MySub(sender As Object, e As EventArgs) lblMsg.text = "<br>Is Your First Name, <b>" & txtFname.text & " </b>?" lblMsg.text += "hmmm, you typed the password, <b>" & txtPwd.text & " </b>right ?" End Sub </script> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Textbox Server Control</h3> <form ID="Form1" runat=server> First Name <asp:TextBox id=txtFname Runat=server /> Password <asp:TextBox id=txtPwd TextMode=Password Runat=server /> <asp:Button Text="Submit" OnClick="MySub" Runat=server /> <asp:Label id=lblMsg ForeColor="#ff0000" Runat=server /> </form> </body> </html> |
In Classic ASP, we have the tag <textarea> to accept values in text area. The same can be achieved in ASP.NET using the textbox web control. We have set the property, "textmode", to "multiline", such as textmode=MultiLine. You can also specify the rows and columns that you may need.
| <html> <head> <title>Textbox Web Server Control - by Das</title> <script language="VB" runat="server"> Sub MySub(sender As Object, e As EventArgs) lblMsg.text = "<br>Is Your First Name, <b>" & txtFname.text & " </b>?" lblMsg.text += "<br>Well, your hobbies seems to be, <b>" & txtHobby.text & "</b>" End Sub </script> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Textbox Server Control</h3> <form ID="Form1" runat=server> First Name <asp:TextBox id=txtFname Runat=server /> Your hobbies <asp:TextBox id=txtHobby TextMode=MultiLine Rows=10 Columns=60 Runat=server /> <asp:Button Text="Submit" OnClick="MySub" Runat=server /> <asp:Label id=lblMsg ForeColor="#ff0000" Runat=server /> </form> </body> </html> |
Another aspect that you may need to note in these examples is, when we click the submit button, all the values are retained in the form without any additional coding. This is the most important feature, Maintaining State, of ASP.NET
Listbox web server control is equivalent to the <Select> tag in HTML. This control will be very useful to get inputs from user, were all values are pre-defined. For eg: inorder to accept the "State in which the user is living", we can have a list of all states available. In this session, we will learn how to populate a listbox control.
Populating a listbox control is very simple. It is the same way as we do in Classic ASP. In classic ASP, we use the <option> tag to add an item to the listbox. In ASP .NET, we use the tag <asp:ListItem> to populate the Listbox.
| <HTML> <HEAD> <title>Listbox Web Server Control - by Das</title> <script language="VB" runat="server"> Sub mySub(sender As Object, e As EventArgs) If lstStates.SelectedIndex > -1 lblMsg.Text = "You selected: " + lstStates.SelectedItem.Text Else lblMsg.Text = "Didn't like any state?" End If End Sub </script> </HEAD> <body style="FONT: 10pt verdana"> <h3align=center>ASP.NET Listbox Server Control</h3> <form ID="Form1" runat=server> <asp:ListBox id=lstStates Rows=1 runat="server"> <asp:ListItem>Florida</asp:ListItem> <asp:ListItem>Georgia</asp:ListItem> <asp:ListItem>Ohio</asp:ListItem> </asp:ListBox> <asp:button Text="Submit" OnClick="mySub" runat="server" id=Button1 /> <asp:Label id=lblMsg ForeColor="#ff0000" Runat=server /> </form> </body> </HTML> |
We can add items to a Listbox control during run time. This is achieved by populating an arrayList. Once we have an arrayList, we can assign this arrayList to the Listbox control. Actually, we have to bind the arrayList to the listbox control. Binding is done using the method DataBind. Before any binding to take place, we should assign a datasource, in our case, it will be the arrayList. The following example does this.
| <HTML> <HEAD> <title>Listbox Web Server Control - by Das</title> <script language="VB" runat="server"> Sub Page_Load(sender As Object, e As EventArgs) If Not IsPostBack Dim arrState As New ArrayList() arrState.Add("Ohio") arrState.Add("Michigan") arrState.Add("Wisconsin") arrState.Add("Indiana") lstStates.DataSource = arrState lstStates.DataBind() End If End Sub Sub mySub(sender As Object, e As EventArgs) If lstStates.SelectedIndex > -1 lblMsg.Text = "You selected: " + lstStates.SelectedItem.Text Else lblMsg.Text = "Didn't like any state?" End If End Sub </script> </HEAD> <body style="FONT: 10pt verdana"> <h3align=center>ASP.NET Listbox Server Control</h3> <form ID="Form1" runat=server> <asp:ListBox id=lstStates Rows=1 runat="server"> </asp:ListBox> <asp:button Text="Submit" OnClick="mySub" runat="server" id=Button1 /> <asp:Label id=lblMsg ForeColor="#ff0000" Runat=server /> </form> </body> </HTML> |
To allow users to select multiple values from a listbox, you need to set two properties, such as rows and SelectionMode. The value for rows can be any integer and for Selectionmode, it will be Multiple. To retrieve the all the values selected by the user, we need to make use of the properties such as Items.Count. And the property, selected will tell us whether the item have been selected or not. See the following example.
| <HTML> <HEAD> <title>Listbox Web Server Control - by Das</title> <html> <head> <script language="VB" runat="server"> Sub mySub(sender As Object, e As EventArgs) If lstStates.SelectedIndex > - 1 lblMsg.Text="" Dim ctr as Integer For ctr=0 to lstStates.Items.Count()-1 If lstStates.items(ctr).selected lblMsg.Text += "<br> You selected <b>" & lstStates.items(ctr).Text & "</b>" end if Next End If End Sub </script> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Listbox Server Control</h3> <form runat=server> <asp:ListBox id="lstStates" Rows="5" SelectionMode="Multiple" runat="server"> <asp:ListItem>Ohio</asp:ListItem> <asp:ListItem>Michigan</asp:ListItem> <asp:ListItem>Wisconsin</asp:ListItem> <asp:ListItem>Texas</asp:ListItem> <asp:ListItem>Dallas</asp:ListItem> <asp:ListItem>Indiana</asp:ListItem> </asp:ListBox><br> <asp:button Text="Submit" Tooltip="To select multiple items hold the CTRL KEY and then select the items" OnClick="mySub" runat="server" /><br> <asp:Label id="lblMsg" runat="server"/> </form> </body> </html> |
If we allow a user to add item to a listbox, then we also may need to allow them to delete items from the listbox. The method remove is used to remove a selected item from the list box. Also, to insert a value to a particular position, say 2nd position, we need to use the method called insert. In the coming example, we will see how to remove an item, insert an item into a particular position and also another method to popopulate a Listbox.
| <HTML> <HEAD> <title>Listbox Web Server Control - by Das</title> <html> <head> <script language="VB" runat="server"> Sub mySub(sender As Object, e As EventArgs) Dim myItem as New ListItem myItem.value="ohio" myItem.text="Ohio" lstStates.items.Add(myItem) myItem=Nothing myItem = New ListItem myItem.value="wisconsin" myItem.text="Wisconsin" lstStates.items.Add(myItem) myItem=Nothing myItem = New ListItem myItem.value="indiana" myItem.text="Indiana" lstStates.items.Add(myItem) End Sub Sub myRemove(sender As Object, e As EventArgs) lstStates.items.Remove(lstStates.selectedItem) End Sub Sub myInsert(sender As Object, e As EventArgs) if Len(Trim(txtAt.text)) > 0 If IsNumeric(txtAt.text) and Cint(txtAt.text) <= lstStates.items.count() lstStates.items.Insert(txtAt.text, "Inserted item") end if end if End Sub </script> </head> <body style="font: 10pt verdana"> <h3 align=center>ASP.NET Listbox Server Control</h3> <form runat=server> <asp:ListBox id="lstStates" Rows="5" SelectionMode="Multiple" runat="server"> </asp:ListBox> <asp:button Text="Populate" OnClick="mySub" runat="server" /> <asp:button Text="Remove" Tooltip="To remove an item, select and then click this button" OnClick="myRemove" runat="server" /> <asp:button Text="Insert" Tooltip="To insert an item, type the position in which you would like to insert." OnClick="myInsert" runat="server" /> at <asp:textbox id="txtAt" runat="server" /> </form> </body> </html> |
Listbox control will be useful to get inputs, which has a pre-determined number of values. Also, you should note that, in the method, PageLoad and mySub we have IF statements. Have you noticed that, we don't have the keyword "Then" for IF statements. "Then" is not mandatory, as it was in classic ASP.
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
Checkbox web server control is equivalent to the <input type=checkbox> tag in HTML. This control can be used to get multiple answers for any given question. In this session, we will see, how can we get the hobbies of any user. We will see the following aspects.
Creating a checkbox is very easy indeed. The following line creates a Checkbox control. <asp:Checkbox Runat=Server />. To assign a text to this checkbox control, we can either do it in the declaration itself, or we can generate the text from server side itself. To assign a text while creating, all you have to do is to use the property text. The following example depicts how to create checkbox web server control and how to assign values from the server side.
| <HTML> <HEAD> <title>Checkbox Web Server Control - by Das </title> <script language=vb runat=server> Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 'Put user code to initialize the page here chkMusic.Text = "Music" chkDriving.Text = "Driving" chkFishing.Text = "Fishing" chkBoating.Text = "Boating" chkEating.Text = "Eating" End Sub Public Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Dim strResult As String = "So, you like <br>" If chkMusic.Checked Then strResult += chkMusic.Text & ", " End If If chkDriving.Checked Then strResult += chkDriving.Text & ", " End If If chkFishing.Checked Then strResult += chkFishing.Text & ", " End If If chkBoating.Checked Then strResult += chkBoating.Text & ", " End If If chkEating.Checked Then strResult += chkEating.Text End If lblResult.Text = strResult & " right?" End Sub </script> </head> <body> <form id="Form1" method="post" runat="server"> <asp:Label ID=lblHobby text="What are your hobbies?" Runat=server /> <asp:CheckBox ID="chkMusic" Runat=server /> <asp:CheckBox ID="chkDriving" Runat=server /> <asp:CheckBox ID="chkFishing" Runat=server /> <asp:CheckBox ID="chkBoating" Runat=server /> <asp:CheckBox ID="chkEating" Runat=server /> <asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat=server /> <asp:Label ID="lblResult" ForeColor="#ff0000" Font-Bold="True" Runat=server /> </form> </body> </HTML> |
The above example is very simple. There are two things to learn from the above example. First, to assign a text to the textbox web server control, you have to use the property text. And to know whether the checkbox has selected or not, you have to use the property checked.
By default, checkbox control does not support the property value. In classic ASP, we used this property to assign any value to the checkbox control. So, in ASP .NET, how to assign a value to the checkbox control. We have to make use of the Attributes method. We have to add an attribute to every checkbox web control. The following line, adds an attribute to the checkbox, Music. chkMusic.Attributes.Add("Value", 1). So, the method add takes two parameters. The first parameter is the attribute name. And the second parameter is the Value for this attribute. In the above example, we have created an attribute called Value. The following example exaplains how to assign attributes and how to retrieve them.
| <HTML> <HEAD> <title>Checkbox Web Server Control - by Das </title> <script language=vb runat=server> Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) 'Put user code to initialize the page here chkMusic.Text = "Music" chkDriving.Text = "Driving" chkFishing.Text = "Fishing" chkBoating.Text = "Boating" chkEating.Text = "Eating" chkMusic.Attributes.Add("Value", 1) chkDriving.Attributes.Add("Value", 2) chkFishing.Attributes.Add("Value", 3) chkBoating.Attributes.Add("Value", 4) chkEating.Attributes.Add("Value", 5) End Sub Public Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Dim strResult As String = "Values for your selections are <br>" If chkMusic.Checked Then strResult += chkMusic.Attributes("Value") & ", " End If If chkDriving.Checked Then strResult += chkDriving.Attributes("Value") & ", " End If If chkFishing.Checked Then strResult += chkFishing.Attributes("Value") & ", " End If If chkBoating.Checked Then strResult += chkBoating.Attributes("Value") & ", " End If If chkEating.Checked Then strResult += chkEating.Attributes("Value") End If lblResult.Text = strResult End Sub </script> </head> <body> <form id="Form1" method="post" runat="server"> <asp:Label ID=lblHobby text="What are your hobbies?" Runat=server /> <asp:CheckBox ID="chkMusic" Runat=server /> <asp:CheckBox ID="chkDriving" Runat=server /> <asp:CheckBox ID="chkFishing" Runat=server /> <asp:CheckBox ID="chkBoating" Runat=server /> <asp:CheckBox ID="chkEating" Runat=server /> <asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat=server /> <asp:Label ID="lblResult" ForeColor="#ff0000" Font-Bold="True" Runat=server /> </form> </body> </HTML> |
Check box controls are very useful control for getting inputs for multiple choice questions.
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
CheckboxList web server control is the same as Checkbox control. Before reading this article, please read my article on CheckBox Web Server Control. In this article we will see how to use the CheckboxList Web server control
CheckBoxList is almost equivalent to the Listbox web server control. The following example explains how to declare a CheckboxList web server control and how to assign and retrieve values depending upon the values selected by the user.
| <HTML> <HEAD> <title>CheckboxList Web Server Control - by Das </title> <script language=vb runat=server> Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Dim ctr As Integer lblResult.Text = "The values for your selection are: " For ctr = 0 To chkBoxList.Items.Count - 1 If chkBoxList.Items(ctr).Selected Then lblResult.Text += chkBoxList.Items(ctr).Value & ", " End If Next End Sub </script> </head> <body style="font: 10pt verdana"> <form id="Form1" method="post" runat="server"> <asp:Label ID=lblHobby text="What are your hobbies?" Runat=server /> <asp:CheckBoxList ID=chkBoxList Runat=server> <asp:ListItem Value=1>Music</asp:ListItem> <asp:ListItem Value=2>Driving</asp:ListItem> <asp:ListItem Value=3>Boating</asp:ListItem> <asp:ListItem Value=4>Fishing</asp:ListItem> <asp:ListItem Value=5>Eating</asp:ListItem> </asp:CheckBoxList> <asp:Button ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" Runat=server /> <asp:Label ID="lblResult" ForeColor="#ff0000" Font-Bold="True" Runat=server /> </form> </body> </HTML> |
The above example is very simple. There are two things to learn from the above example. First, to create an item for checkbox, you have to use the <asp:ListItem> tag. Then we use the attribute Value to assign values to the individual checkbox item. This is the same as the ListBox Server control.
CheckBoxList controls are very useful control for getting inputs for multiple choice questions.
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
RadioButton Web Server Control is perfect for questions who has only one answer. The RadioButton web server control is almost the same as the CheckBox web server control. The only thing that is different here is that, you have to use a property called GroupName to the collection of your radio buttons. Other than that it is the same as the Checkbox control.
To assign a text, we need to use the text property and to know whether the radio button have been selected, we need to use the selected property, which returns either true or false.
| <HTML> <HEAD> <title>RadioButton Web Server Control - by Das </title> <script language=vb runat=server> Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) rd1.Text = "Doctor" rd2.Text = "Software Engineer" rd3.Text = "Lawyer" rd4.Text = "Business Man" rd5.Text = "Other" End Sub Public Sub btnSubmit_OnClick(ByVal sender As Object, ByVal e As EventArgs) If rd1.Checked Then lblResult.Text = "So, you are a " & rd1.Text & " (Any surgeries so far?)" ElseIf rd2.Checked Then lblResult.Text = "So, you are a " & rd2.Text & " (So you work with Computers, right)" ElseIf rd3.Checked Then lblResult.Text = "So, you are a " & rd3.Text & " (How may cases have you attended so far?)" ElseIf rd4.Checked Then lblResult.Text = "So, you are a " & rd4.Text & " (Self employeed, huh)" ElseIf rd5.Checked Then lblResult.Text = "So, you are a " & rd5.Text & " (What else you are, just curious?)" Else lblResult.Text = "OOPS! you selected nothing! Try again." End If End Sub </script> </head> <body> <form id="Form1" method="post" runat="server"> <h3>ASP .NET Tutorial: Working with Radio Button Control. <asp:Label ID="lblMsg" Text="What is your profession?" Runat=server
/> |
You can also add attributes and retrieve attributes for this control. To know more about adding and retrieving attributes, please read my article on Checkbox web server control.
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
A web developer is routinely faced with the challenge of
knowing which link was clicked. The typical solution involves passing
information on the querystring in the clear, like this: "GetProduct.asp?ID=3762".
A key benefit of the LinkButton web control is the power to know which link was
clicked by using POST rather than GET. This is accomplished by setting 2
properties on the LinkButton: CommandName and CommandArgument.
These properties are passed into the onCommand event when the user clicks a
LinkButton. In the event handler for onCommand, the CommandName and
CommandArgument properties can be evaluated in CommandEventArgs. Because this
all takes place in the POST, the querystring is shorter and the postback data is
hidden.
Let's begin by looking at some code. First, a "mini" database of products is
created in the code using two instances of System.Collection.Hashtable. One
hashtable stores the ProductId and ProductTitle, and the other hashtable stores
the ProductId and ProductDescription. The two Hashtables are related by the
ProductId. This technique is OK for demonstration purposes; however, there are
cleaner ways to accomplish this.
|
Hashtable
hashProductName =
new Hashtable(); Hashtable hashProductDesc = new Hashtable(); void BuildMiniDatabase() { hashProductName[0] = "Jalapeno Dip" ; hashProductDesc[0] = "Simmered in mayonaise and wine, this Jalapeno Dip will make your eyes water" ; hashProductName[1] = "Smoked Sausage" ; hashProductDesc[1] = "Mouth watering and delicious sausage" ; hashProductName[2] = "Shrimp Fiesta" ; hashProductDesc[2] = "East Coast's finest shrimp" ; hashProductName[3] = "Jerk Chicken" ; hashProductDesc[3] = "A real island experience you will not forget" ; hashProductName[4] = "Beer-Battered Fish" ; hashProductDesc[4] = "Pabst Blue Ribbon and Fish. Wow!" ; hashProductName[5] = "Bacon Burger" ; hashProductDesc[5] = "Big, juicy, and bursting with flavor" ; hashProductName[6] = "Sirloin Tip" ; hashProductDesc[6] = "Delicate cuts with no fat" ; hashProductName[7] = "Baked Alaska" ; hashProductDesc[7] = "Fine dessert comprised of sponge cake topped with ice cream and covered with meringue. The meringue is browned before the ice cream can melt." ; hashProductName[8] = "Fried Chicken" ; hashProductDesc[8] = "Country cookin'" ; hashProductName[9] = "Fresh Garden Salad" ; hashProductDesc[9] = "Crispy iceberg lettuce and a garden of vegtables" ; hashProductName[10] = "One Pea" ; hashProductDesc[10] = "A single green pea that will leave you craving more" ; } |
Next, the web page layout is very basic. Inside a form, a table is built with 2 columns. The left side cell will hold the product links. The right cell will display the product description.
|
<body> <form id="MainForm" method="post" runat="server" > <asp:Table CellPadding=6 CellSpacing=2 BorderColor="#DDDDDD" BorderStyle=Solid BorderWidth=2 Runat=server> <asp:TableRow Runat=server> <asp:TableCell id=LinkList Wrap=False BackColor="#FFFFFF" Runat=server/> <asp:TableCell id="tablecellMessage" CssClass="ProductDesc" Runat=server></asp:TableCell> </asp:TableRow> </asp:Table> </form> </body> |
Now that the web page is designed, the LinkButtons can be added. The LinkButtons are added dynamically using code. The System.Web.UI.WebControls.LinkButton control is instantiated and assigned to _LB1. The Text property is used for rendering the hyperlink label. That is, the text that sits between <a></a>. The CommandName and CommandArgument are what's it all about. Use the CommandArgument property to specify an argument that complements the CommandName property. What might have been placed on the querystring, will now simply be assigned in the CommandName and/or CommandArgument properties. In my example, I'm really just using the CommandArgument property for storing the ProductId of each product link. The CommandName is used to identify my grouping of links which happen to be the same - they're all products.
| void BuildLinkList() { for (int i=1; i<=10; i++) { LinkButton _LB1 = new LinkButton(); _LB1.Text = hashProductName[i].ToString(); _LB1.CssClass = "ProductLinks"; _LB1.CommandName = "Products"; _LB1.CommandArgument = i.ToString() ; |
The onCommand event is fired when a user clicks a LinkButton. Because my LinkButtons are added programatically, I need to wire the onCommand event to the control and assign it to the OnLinkClick event handler.
|
_LB1.Command += new System.Web.UI.WebControls.CommandEventHandler(OnLinkClick); LinkList.Controls.Add(_LB1); LinkList.Controls.Add(new LiteralControl("<br>")); |
When the user clicks a product link, the OnLinkClick event handler will determine which link was clicked, get the ProductId from the CommandArgument property, retrieve the ProductDescription from the mini database, and display the result on the web page.
|
void OnLinkClick(object O, System.Web.UI.WebControls.CommandEventArgs
E) { int RecordId = Int32.Parse(E.CommandArgument.ToString()); tablecellMessage.Text = "<b>" + hashProductName[RecordId].ToString() + "</b><br><i>" + hashProductDesc[RecordId].ToString() + "</i>"; } |
The LinkButton web control will most likely become a fundamental part of your ASP.Net programming.
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
One of the frequent task in any web application is dealing with the text files. In classic ASP, we used the FileSystemObject to deal with files. In this article, we will see how to create text files in ASP .NET.
We require the namespace,
System.IO to work with files. So, we should import this namespace in our ASPX
page such as
<%@ Import Namespace="System.IO" %>
To start with, we need to create an instance of the object, StreamWriter. The instance will be the file pointer for us. Once we have a File Pointer, we need to invoke the method, CreateText method of the object, File. The method, CreateText takes a string as an argument. The string is nothing but the path of file that is going to get created. Now, let us see an example. Let us assume, we have a textbox with textmode set to MultiLine and a button. On the click event of the button, we need to create a text file. The code within the Click event is shown below.
| Sub WriteToFile(sender
As Object, e As EventArgs) Dim fp As StreamWriter Try fp = File.CreateText(Server.MapPath(".\Upload\") & "test.txt") fp.WriteLine(txtMyFile.Text) lblStatus.Text = "File Succesfully created!" fp.Close() Catch err As Exception lblStatus.Text = "File Creation failed. Reason is as follows " & err.ToString() Finally End Try End Sub |
We are first creating an instance of StreamWriter, which is termed as fp (file pointer). Then, in the Try block, we invoke the CreateText method. To write the content, we use the method, WriteLine. Actually, we have just three lines of code which writes data to a text file. Once we have successfully written to the text file, we close the StreamWriter by invoking the Close method of StreamWriter.

Fig: Creating Text Files in ASP .NET
Creating a text file is very easy. We can easily create a text file in just 3 lines of code.
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
This article is a continuation of the article, Creating Text Files in ASP .NET. In this article, we will see read the text file which we created earlier.
We require the namespace,
System.IO to work with files. So, we should import this namespace in our ASPX
page such as
<%@ Import Namespace="System.IO" %>
To start with, we need to create an instance of the object, StreamReader. The instance will be the file pointer for us. Once we have a File Pointer, we need to invoke the method, OpenText method of the object, File. The method, OpenText takes a string as an argument. The string is nothing but the path of file that is going to get created. Now, let us see an example. Let us assume, we have a textbox with textmode set to MultiLine and a button. On the click event of the button, we need to read the text file. The code within the Click event is shown below.
| Sub WriteToFile(sender
As Object, e As EventArgs) Dim fp As StreamReader Try fp = File.OpenText(Server.MapPath(".\Upload\") & "test.txt") txtMyFile.Text = fp.ReadToEnd() lblStatus.Text = "File Succesfully Read!" fp.Close() Catch err As Exception lblStatus.Text = "File Read Failed. Reason is as follows " & err.ToString() Finally End Try End Sub |
We are first creating an instance of StreamReader, which is termed as fp (file pointer). Then, in the Try block, we invoke the OpenText method. To read the content, we use the method, ReadToEnd. Actually, we have just three lines of code which reads content from a text file. Once we have read the content from the text file, we close the StreamReader by invoking the Close method of StreamReader.
Reading a text file is just the same way as creating the textfile. We can also use the method Read or ReadLine to read data from a text file.
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET
Asking the user to upload a file to the server is a very very common task in most of the web applications. In classic ASP, uploading file was a very difficult task, since we need a third party component or we need to write our component to upload file from client to the server. In ASP .NET Uploading a file from client to the web server is so easy. To be precise, we can get this done in two lines of code. Yes, two lines of code. In this article, we will be looking into the following:
First of all, we need a HTML server control to allow the user
to select the file. This is nothing but the same old <input tag, with the type
set to File, such as <input type=file id=myFile runat=server />.
This will give you the textbox and a browse button. Once you have this, the user
can select any file from their computer (or even from a network). Then, in the
Server side, we need the following line to save the file to the Web Server.
myFile.PostedFile.SaveAs("DestinationPath")
Example: Uploading a File in ASP .NET
| <html> <head> <script language="VB" runat="server"> Sub Upload(Source As Object, e As EventArgs) If Not (myFile.PostedFile Is Nothing) Then Dim intFileNameLength as Integer Dim strFileNamePath as String Dim strFileNameOnly as String 'Logic to find the FileName (excluding the path) strFileNamePath = MyFile.PostedFile.FileName intFileNameLength = Instr(1, StrReverse(strFileNamePath), "\") strFileNameOnly = Mid(strFileNamePath, (Len(strFileNamePath)-intFileNameLength)+2) myFile.PostedFile.SaveAs("c:\inetpub\wwwroot\yourwebapp\upload\" & strFileNameOnly) lblMsg.Text = "File Upload Success." End If End Sub </script> </head> <body> <h3>File Upload</h3> <form enctype="multipart/form-data" runat="server"> File: <input id="myFile" type="file" runat="server"> <asp:label id=lblMsg runat="server" /> <input type=button value="Upload" OnServerClick="Upload" runat="server"> </form> </body> </html> |
In the above example, you should note that, in the FORM tag, we have set the ectype to "multipart/form-data". This is another important aspect while uploading a file to the web server. We have a Input tag which is of type file. Then we have a button called "Upload". On the onclick of the button, you can see that, we are using some string functions to find the FileName (excluding the path). Finally, we invoke the method SaveAs to save the file (upload) in the web server.
We can retrieve some of the interesting and useful properties
of the file that is uploaded to the webserver. The PostedFile provides us with
three important properties, such as FileName, ContentType and ContentLength. In
our previous example, we already saw, how to use the property, FileName? Now, we
will see, how to know the size of the file uploaded, and how to know the
contentType of the file uploaded.
The following line of code retrieves the ContentType of the file uploaded.
lblFileContentType.Text = MyFile.PostedFile.ContentType
The following line of code retrieves the Size of the file uploaded.
lblFileSize.Text = CStr(MyFile.PostedFile.ContentLength)
Now, we will see an example which uses this property.
Example: Uploading a File in ASP .NET
| <html> <head> <script language="VB" runat="server"> Sub Upload(Source As Object, e As EventArgs) If Not (myFile.PostedFile Is Nothing) Then Dim intFileNameLength as Integer Dim strFileNamePath as String Dim strFileNameOnly as String 'Logic to find the FileName (excluding the path) strFileNamePath = MyFile.PostedFile.FileName intFileNameLength = Instr(1, StrReverse(strFileNamePath), "\") strFileNameOnly = Mid(strFileNamePath, (Len(strFileNamePath)-intFileNameLength)+2) myFile.PostedFile.SaveAs("c:\inetpub\wwwroot\yourwebapp\upload\" & strFileNameOnly) lblMsg.Text = "File Upload Success." lblFileContentType.Text = "Content type: " & MyFile.PostedFile.ContentType lblFileSize.Text = "File size: " & CStr(MyFile.PostedFile.ContentLength) & " bytes" End If End Sub </script> </head> <body> <h3>File Upload</h3> <form enctype="multipart/form-data" runat="server"> File: <input id="myFile" type="file" runat="server"> <input type=button value="Upload" OnServerClick="Upload" runat="server"> <asp:label id=lblMsg runat="server" /> <asp:label id=lblFileContentType runat="server" /> <asp:label id=lblFileSize runat="server" /> </form> </body> </html> |
While uploading a file to the web server, we have a limit of
4MB by default. We can either decrease or increase this value. The value is set
in the key, maxRequestLength of machine config file.
There is a maxRequestLength limit in the machine.config file (look for the <system.web>
section), in the httpRuntime settings that you need to alter/raise if you want
to accept anything larger than 4Mb. These are the standard settings for the
httpRuntime:
<httpRuntime executionTimeout="90" maxRequestLength="4096"
useFullyQualifiedRedirectUrl="false" minFreeThreads="8"
minLocalRequestFreeThreads="4" appRequestQueueLimit="100"/>
Label Web Server Control
Textbox Web Server
Control
Listbox Web Server
Control
CheckBox Web Server
Control
CheckBoxList Web
Server Control
RadioButton Web
Server Control
.NET LinkButton
web control
How to Create a text file in ASP
.NET
How to Read a text file in ASP
.NET
How to Upload files in ASP .NET