Parag’s Den

Dedicated to my adored friends…..

Archive for the ‘– Asp.Net’ Category

Label Web Server Control

Posted by paragdongre on November 6, 2007

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.

  1. How to display/assign a text with Label Web server control?
  2. How to assign a borderwidth?
  3. How to give colors for our text?
Label – How can we declare a Label control?

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>

Label – How to dynamically assign text to a Label?

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>

Label – How to show tooltip, borderwidth, forecolor, bgcolor etc.

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>

Posted in - Asp.Net | Leave a Comment »

Textbox Web Server Control

Posted by paragdongre on November 6, 2007

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 ..

  1. Get an input from the user
  2. Create a textarea
  3. Get passwords as input
Textbox and Button

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>

Password

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>

TextArea

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>

Posted in - Asp.Net | Leave a Comment »

Listbox Web Server Control

Posted by paragdongre on November 6, 2007

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.

  1. How to populate a Listbox control
  2. Populating the listbox during runtime, using Databinding
  3. Selecting Multiple items in a Listbox
  4. How to Remove items
  5. Insert items to a particular position
ListBox – 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>

How to dynamically populate a Listbox control?

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>

Selecting Multiple items in a Listbox

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>

How to Remove items and to Insert items to a particular position?

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>

Posted in - Asp.Net | 1 Comment »

CheckBox Web Server Control

Posted by paragdongre on November 6, 2007

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.

  1. How to assign a text to Checkbox control?
  2. How to know whether the checkbox has been checked or not?
  3. How to assign a value to Checkbox control?
  4. How to add an attribute to a CheckBox Control?
  5. How to retrieve an attribute from a CheckBox Control?
Checkbox – How to assign a text to Checkbox control and how to know the checkboxes that are selected?

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.

Checkbox – How to assign a Value to the Checkbox control?

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>

Posted in - Asp.Net | Leave a Comment »

CheckBoxList Web Server Control

Posted by paragdongre on November 6, 2007

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

  1. How to assign text and retrieve values from a CheckboxList control?
  2. How to go through all the elements inside a CheckBoxList?
  3. How to find the selected items in a CheckBoxList?
CheckboxList – How to assign a text to and how to retrieve the values?

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>

Posted in - Asp.Net | Leave a Comment »

RadioButton Web Server Control

Posted by paragdongre on November 6, 2007

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.

  1. How to assign a text to Radio Button control?
  2. How to know which RadioButton has been selected by the user?
RadioButton – How to assign a text how to know radio button have been selected?

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 />
     <asp:RadioButton ID=”rd1″ GroupName=profession Runat=server />
     <asp:RadioButton ID=”rd2″ GroupName=profession Runat=server />
     <asp:RadioButton ID=”rd3″ GroupName=profession Runat=server />
     <asp:RadioButton ID=”rd4″ GroupName=profession Runat=server />
     <asp:RadioButton ID=”rd5″ GroupName=profession Runat=server />
     <asp:Button ID=”btnSubmit” Text=”Submit” OnClick=”btnSubmit_OnClick” Runat=server />
     <asp:Label ID=”lblResult” ForeColor=”#ff0000″ Font-Bold=”True” Runat=server />

</form>

</body>
</HTML>

Posted in - Asp.Net | Leave a Comment »

How to Create a text file in ASP .NET?

Posted by paragdongre on November 6, 2007

Introduction

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.

Things that we will be learning in this article
  1. The namespace that is required to deal with Files
  2. The StreamWriter Object
  3. Creating a Text File
  4. How to capture errors which may occur while creating a text file?
The Namespace that is required to deal with Files

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” %>

How to Create a text File?

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.

Code in the OnClick event of button.
    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

How it works?

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.

Posted in - Asp.Net | Leave a Comment »

How to Read a text file in ASP .NET?

Posted by paragdongre on November 6, 2007

Introduction

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.

Things that we will be learning in this article
  1. The namespace that is required to deal with Files
  2. The StreamReader Object
  3. Reading a Text File
  4. How to capture errors which may occur while reading a text file?
The Namespace that is required to deal with Files

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” %>

How to Read a text File?

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.

Code in the OnClick event of button.
    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

How it works?

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.

Posted in - Asp.Net | Leave a Comment »

Sending Emails from ASP .NET

Posted by paragdongre on November 6, 2007

Sending email is a very common task in any web application. In almost every web application (web site), their will atleast be an occassion to send email in any fashion. In classic ASP, we worked with the CDONTS object to send emails from an ASP page. The SmtpMail class in ASP .NET provides properties and methods for sending messages using the Collaboration Data Objects for Windows 2000 (CDOSYS) message component In this article, we will see, how can we send email from an ASP .NET page. In a nut shell, today, we will be looking into the following:

  1. What we need to send Email from an ASP .NET?
  2. How to send an email from an ASP .NET page?
  3. What is new in sending email? (SmtpMail.SmtpServer)
  4. How can we send attachments in an email?

What we need to send Email from an ASP .NET?

The first thing that you need is the SMTP service. SMTP service should be up and running. And you also need to import the namespace, System.Web.Mail. To create a mail object, you need to create an instance of MailMessage. MailMessage has all required properties such as To, Subject, BCC, CC etc. For a complete list of method and properties, that you can make use of, please visit http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebMailMailMessageMembersTopic.asp.

How to send an email from an ASP .NET page?
<%@ Import Namespace=”System.Web.Mail” %><html>

<script language=”VB” runat=”server”>
Sub Page_Load(Sender As Object, E As EventArgs)

     Dim msg as New MailMessage()

     msg.To = “das@silicomm.com”
     msg.From = “das@aspalliance.com”
     msg.Subject = “test”
     ‘msg.BodyFormat = MailFormat.Html
     msg.BodyFormat = MailFormat.Text
     msg.Body = “hi”

     SmtpMail.SmtpServer = “localhost”

     SmtpMail.Send(msg)
     msg = Nothing
     lblMsg.Text = “An Email has been send to ” & “das@silicomm.com”

End Sub
</script>

<body style=”font: 10pt verdana”>
<form runat=server>
<asp:Label id=lblMsg runat=Server /> </form>
</body>
</html>

In the above example, we start the coding by importing the namespace, “System.Web.Mail”. Then, in the Page_Load event, we create an instance of MailMessage object. It is through the MailMessage object, we set all the properties such as To, From, Subject, Body etc. We can either send a text message or a html message. We need to specify the bodyformat in the BodyFormat property. One we set all the properties, it is ready to send the email. Before sending the email, you have to set another important property, ie; SmtpServer. You have to set this property. You should assign the name of your SMTP server to this property. In most cases you can assign this as “localhost”. If you do not set this property, then you will not be able to send email from an ASP .NET page. Finally we send the email using SmtpMail.Send. This methods expects the MailMessage as an argument. Actually the method Send is overloaded. You can also send an email by specifiying, SmtpMail.Send (From, To, subject, body). To see the complete overloaded list, please visit http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebMailMailMessageMembersTopic.asp

How can we send attachments in an email?

To send attachments, we need to add attachments using the Add method, which is available in the Attachments object. The only thing that we need to add to the above example is msg.Attachments.Add (New MailAttachment(Server.MapPath(“filename.ext”)))

<%@ Import Namespace=”System.Web.Mail” %><html>

<script language=”VB” runat=”server”>
Sub Page_Load(Sender As Object, E As EventArgs)

     Dim msg as New MailMessage()

     msg.To = “das@silicomm.com”
     msg.From = “das@aspalliance.com”
     msg.Subject = “test”
     ‘msg.BodyFormat = MailFormat.Html
     msg.BodyFormat = MailFormat.Text
     msg.Body = “hi”

     msg.Attachments.Add (New MailAttachment(Server.MapPath(“EMAIL1.ASPX”)))

     SmtpMail.SmtpServer = “localhost”

     SmtpMail.Send(msg)
     msg = Nothing
     lblMsg.Text = “An Email has been send to ” & “das@silicomm.com”

End Sub
</script>

<body style=”font: 10pt verdana”>
<form runat=server>
<asp:Label id=lblMsg runat=Server /> </form>
</body>
</html>

Enhancements that you add to the above examples.

We can add any number of attachments to an email. To send multiple attachments, just repeat the line Msg.Attachments.Add with the file that needs to be attached. Also, it will be a good practice to add a try…catch…finally block before invoking the Send Method. Since any error can occur while sending an email such as smtp service not running, smtp server busy and many more.

Posted in - Asp.Net | Leave a Comment »

How to Upload files in ASP .NET

Posted by paragdongre on November 6, 2007

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:

  1. How to Upload a file from Client to the Web server in ASP .NET?
  2. How to give a different name to the file saved to the web server?
  3. How to know the size of the file uploaded by the user?
  4. How to control the size of file uploaded to the web server?

How to Upload a file from Client to the Web server in ASP .NET?

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.

How to retrieve the properties of file uploaded by the user?

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>

How to control the size of file uploaded to the web server?

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″/>

Posted in - Asp.Net | Leave a Comment »