ASP.net Tutorial for beginners

Document Sample
ASP.net  Tutorial for beginners Powered By Docstoc
					                               Label Web Server Control

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.

      How to display/assign a text with Label Web server control?
      How to assign a borderwidth?
      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>


Test this Script
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>


Test this Script
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>


Test this Script
Send your comments to     das@aspalliance.com              Back to Tutorial
                            Textbox Web Server Control

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

      Get an input from the user
      Create a textarea
      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>


Test this Script
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>


Test this Script
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>


Test this Script
Conclusion

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

Send your comments to   das@aspalliance.com           Back to Tutorial
                             Listbox Web Server Control

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.

      How to populate a Listbox control
      Populating the listbox during runtime, using Databinding
      Selecting Multiple items in a Listbox
      How to Remove items
      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>


Test this Script
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>


Test this Script
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>


Test this Script
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>


Test this Script
Conclusion

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.

Send your comments to   das@aspalliance.com           Back to Tutorial
Copyright © 2000-2003 ASPAlliance.com Page Rendered at 12/23/2009 8:35:34 PM
Copyright © 2000-2003 ASPAlliance.com Page Rendered at 12/23/2009 5:52:21 PM
                                                           Written on: July, 18th 2002.
DataGrid and DropDownLists
                                  Introduction

   DropDownLists are very useful controls which can be used to accept input
from users. This control can be better used, if we know the range for the input.
 User feels more comfortable with DropDownLists (combo boxes) rather than
  textbox, since keyboard should be used to provide input to the latter. In this
  article, we will see how can we use a dropdownlist inside a datagrid. We will
take the table, "stores" which is available under the database pubs (SqlServer
                                     2000).

  One of the field in the table, "stores" is state. We will create another lookup
 table to store the values of states available in United States. We are going to
 create an editable datagrid. In the view mode, we will have just Labels. When
   we switch to the edit mode, we will allow the user to modify the state, by
                              means of dropdownlist.

        I assume that, the reader knows to create a simple datagrid with
                   TemplateColumn and ItemTemplate tags.

                  Things that we will be learning in this article

      How to populate a DataGrid?
      How to populate a dropdownlist within a datagrid?
      How to pick the Selected Item from a dropdownlist?
      How to preset items in a dropdownlist (which is in the edit mode)?

                            Populating the DataGrid

 For our example, we will take the table STORE in the PUBS Database. Since
  stored procedures are very much better than inline query, we use a stored
procedure called, sp_stores_sel, which contains a single SQL statement. The
               SQL statement would be Select * from stores.

              How to populate a dropdownlist within a datagrid?

 The important aspect that is to be noted is that, we cannot explicitly bind the
dropdownlist from the page_load event or any other method. The dropdownlist
 control in a <EditTemplateColumn> is only accessible to the Update Method
             (which is specified in the OnUpdateCommand event).

But, while declaring the dropdownlist, we can invoke a method/function which
will return the datasource for the dropdownlist. We should also specify values
 for the properties DataTextField and DataTextValue. The contents of the field
specified in DataTextField will be used to fill the text section of the combo box.
 And the property, DataTextValue will be used to fill the value property of the
                 combo box (HTML Select tag). </FONT< p>

                     <EditItemTemplate> of the DataGrid

  <EditItemTemplate>
    <asp:Label ID="lblTempState"
       Text='<%# DataBinder.Eval(Container.DataItem, "state") %>'
       Runat=server />

    <asp:DropDownList id="cboState"
       DataSource="<%# BindState() %>"
       DataTextField="Statename"
       DataTextValue="Statename"
       runat="server" />
  </EditItemTemplate>




                                How it works?

 The most important piece of code in the above example is DataSource="<%#
   BindState() %>". We invoke a method called BindState, which in turn will
   return the DataSource for the DropDownlist. We will be looking into this
 method shortly. Also, we need to specify the text that will be displayed in the
dropdown and so as the value for each text. We can assign the text by setting
the property, DataTextField and the value can be specified using the property,
 DataTextValue. We have to specify the field names for both the fields. In our
           example, we use the field, StateName for both properties.

                      DataSource for the DropDownList

  Private Function BindState()
     Dim myConnection As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
     Dim myCommand As SqlCommand = New SqlCommand("sp_das_state_sel",
myConnection)

    myCommand.CommandType = CommandType.StoredProcedure

    myConnection.Open()
    Return myCommand.ExecuteReader(CommandBehavior.CloseConnection)
  End Function
                                  How it works?

       The method BindState just executes a stored procedure called
  sp_das_state_sel. The last statement in this method, the return statement,
    actually returns a DataSource. This is how we set the DataSource for
DropDownList, which is in the Edit Mode of a DataGrid. The above sample did
 not have any error handling. But I have provided the entire aspx page at the
     download section. You can also see the sample output and a demo.

              How to pick the Selected Item from a dropdownlist?

 In this last section, we will see how to get the selected/updated item from the
   dropdownlist. We know that, we show the dropdownlist only during the edit
    mode. When the user clicks the update button, we have to get the selected
  item in the combo box. The following two lines of code does this. First let us
                               take a look at the code.

Dim cboStateTemp As DropDownList = CType(e.Item.FindControl("cboState"),
DropDownList)
Dim strTemp as String = cboStateTemp.SelectedItem.Value




                                  How it works?

   First, we use the Findcontrol method to get the combo box object. After the
first statement, we have a dropdownlist object named, cboStateTemp. Note the
    type casting done using the Ctype method. Once we have a dropdownlist
object, we can work with all properties and methods that are available in in this
   object. The property to get the selected value is SelectedItem. We need the
   value, so we have to say, SelectedItem.Value. If you need the text, then you
                         have to say, SelectedItem.Text.

      How to preset items in a dropdownlist (which is in the edit mode)?

 This is the most tricky part of this article. The event that will be helpful for us
    to do this operation in the ItemDataBound event. So, in the datagrid, you
should invoke a method for this event. Then, in the event, all we need is to find
the control "cbostate" and set the SelectedIndex property. Apart from this, we
  need to know which item we need to preset. Well, we can get this value from
 the edit event. If you do a FinControl on the Edit Event for the column that we
need the value (in our case, the state column), we will get the value that needs
   to be preset. Plese see the following piece of code in the ItemDataBound
                                       event.
                             ItemDataBound Event

Private Sub DG_ItemDataBound(s as object, e as DataGridItemEventArgs)
   If e.item.itemType = ListItemType.EditItem Then
      Dim myDropDown as DropDownList
      myDropDown = Ctype(e.Item.FindControl("cbostate"), DropDownList)
      myDropDown.SelectedIndex =
myDropDown.Items.IndexOf(myDropDown.items.findbytext(strCurrentState))
   End If
End Sub




                                 How it works?

  In the above event, we just have three lines of code. The first two statements
inside the IF statement is pretty straight forward. The third one is the important
        line, which presets the item in the combo box. The string variable,
 strCurrentState is populated in the Edit event and is a global variable. You can
                  download the complete code later in this article.

                         Sample output of our scenario




                        Fig: DataGrid with Combo Box.

                                 Test this Script

                               Download the code

                    Click here to download the ASPX page
                 Click here to download the Stored Procedure

                                   Conclusion

I have used stored procedures in all places. For your convenience, I have also
 included source code for these stored procedures. If you have any questions
    regarding this article or any of my article please feel free to email me at
                      das@aspalliance.com

                              Links

                      How to Edit a DataGrid?
         How to capture a Double Click event in DataGrid?
                  Checkbox Web Server Control
          Retrieving Images from SqlServer in ASP .NET
  Retrieving Images from SqlServer and displaying it in DataGrid

Send your comments to das@aspalliance.com        Back to Article list
Copyright © 2000-2003 ASPAlliance.com Page Rendered at 12/23/2009 8:42:11
                                   PM
                           CheckBox Web Server Control

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.

      How to assign a text to Checkbox control?
      How to know whether the checkbox has been checked or not?
      How to assign a value to Checkbox control?
      How to add an attribute to a CheckBox Control?
      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>


Test this Script

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>


Test this Script

Conclusion

Check box controls are very useful control for getting inputs for multiple choice
questions.

Send your comments to    das@aspalliance.com              Back to Tutorial




                          CheckBoxList Web Server Control

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

      How to assign text and retrieve values from a CheckboxList control?
      How to go through all the elements inside a CheckBoxList?
      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>


Test this Script
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.

Conclusion

CheckBoxList controls are very useful control for getting inputs for multiple choice
questions.

Send your comments to   das@aspalliance.com            Back to Tutorial

                          RadioButton Web Server Control

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.

      How to assign a text to Radio Button control?
      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>


Test this Script
Conclusion

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.

Send your comments to   das@aspalliance.com          Back to Tutorial
Net LinkButtons
Author:    Troy Karhoff

Language: C#                 Live Demo




This article covers a fundamental use of the .NET LinkButton web control for page
postbacks.

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.

Download

Click here to download the source code
Demo

For a demo, please click this link.

Links

Label Web Server Control
ListBox Web Server Control
CheckBox Web Server Control

Send your comments to tkarhoff@msn.com   Back to Article list
Copyright © 2000-2003 ASPAlliance.com Page Rendered at 12/23/2009 8:39:39 PM




                                        Panels" can do wonders!

This article was contributed by Rajiv. R and he can be reached at rajiv.raj@wipro.com.

I saw my team mates develop wizards in our web-based application development
project, that involved multiple steps, back & forth movement (with "next" and "back"
buttons), and data being saved only in the last step.

I saw them code to persist data across pages (steps of the wizard) and in the process
loaded the Session object.

I always wondered if ASP.NET's viewstate capabilities be put to good use! Some
conceptual thinking resulted that use of "Panel" web control could be a boon!

Zooooom came an opportunity, thanks to an enhancement request from the client! :)

I was assigned a fairly simple wizard with about 4 steps. The methodology, I followed
was this.

1. For every step of the wizard, I put a Panel web control.
2. One Set of "Cancel", "Next", "Back" & "Save" buttons at the bottom.
3. In the event handlers of these buttons, hide/unhide the panels and hide/unhide the
buttons.
4. In the last step, unhide Save button and in the event handler, you have access to all
the data across steps with no hassles!

The user gets a feel that each step is a different page, but as a developer, I had an easy
time! Across the steps, I did just nothing to persist data. ASP.NET ViewState did it for
me!

And at the last click, I had all the data in page to be saved! No hassles!

DownLoad

WizardDemo.Zip (22 KB)

This article was contributed by Rajiv. R and he can be reached at rajiv.raj@wipro.com.

Other articles written by Rajiv.R

Displaying Files with a Hyperlink to dowload it

Click here to read articles written by other contributors.



How to Create a text file in ASP .NET?                                         Written on: May, 13th 2002.


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

       The namespace that is required to deal with Files
       The StreamWriter Object
       Creating a Text File
       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. </FONT< p>

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.

Sample output of our scenario




Fig: Creating Text Files in ASP .NET


Test this Script

Download the code

Click here to download the ASPX page

Conclusion

Creating a text file is very easy. We can easily create a text file in just 3 lines of code. To
read content from a text file, visit my article Read data from Text File

Links

Textbox Web Server Control
Reading data from a Text File

Send your comments to     das@aspalliance.com             Back to Tutorial


Populating DropDownList - The key aspect                            Written on: Sept 5th 2002.
that needs to be noted

Some times you may notice that, you are getting the following values in your
dropdownlists.

<option
value="System.Data.DataRowView">System.Data.DataRowView</option>
When binding to the DropDownList (and some of the other controls), you need to specify
the DataTextField and DataValueField (if you don't specify the DataValueField then the
control will automagically use what you specified for the DataTextField).

Something like this....

DropDownList1.DataTextField = "FieldNameThatIsToBeDisplayedForEachItem"
DropDownList1.DataValueField = "FieldNameThatRepresentsTheValueOfTheItem
Copyright © 2000-2003 ASPAlliance.com Page Rendered at 12/23/2009 5:11:14 PM




                                                                               Written on: Aug 16th 2002.
DataGrid with Multiple DropDownLists

Introduction

This article is continuation of DataGrid and DropDownList.

In this article, we will discuss about populating a DropDownList based on the
SelectedItem from a different DropDownList. In other words, how to populate
DropDownLists which has a master detail relationship.

BackBone of this article


<asp:DropDownList id="cboState"
      OnSelectedIndexChanged="PopulateNextCombo"
      AutoPostBack="True"
      runat="server" />




How it works?

The above declaration pertains to the master DropDownList. Please note that, the
AutoPostBack is set to true. This is the key aspect. When a user changes the current
value in the master DropDownList, we should populate the child DropDownList. That is
why, we have set the OnSelectedIndexChanged property.

PopulateNextCombo


Public Sub PopulateNextCombo(ByVal sender As Object, ByVal e As System.EventArgs)
   Dim tmpcboState2 As DropDownList
   Dim tmpDropDown1 as DropDownList
   Dim myConnection As SqlConnection = New
SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
   Dim myCommand As SqlCommand = New SqlCommand("sp_das_state_sel",
myConnection)
   Dim myDataReader As SqlDataReader

    myCommand.CommandType = CommandType.StoredProcedure
    Try
        myConnection.Open()
        myDataReader =
myCommand.ExecuteReader(CommandBehavior.CloseConnection)
      tmpcboState2 =
CType(DG_Combo.Items.Item(DG_Combo.EditItemIndex).FindControl("cboState2"),
DropDownList)
      tmpcboState2.DataSource = myDataReader
      tmpcboState2.DataBind()
      tmpDropDown1 =
CType(DG_Combo.Items.Item(DG_Combo.EditItemIndex).FindControl("cboState"),
DropDownList)
      tmpcboState2.SelectedIndex = tmpDropDown1.SelectedIndex

   Catch SQLexc As SqlException
      lblStatus.Text = "Error while Generating Data. Error is " & SQLexc.ToString()

   Finally
      If Not myDataReader Is Nothing Then
           myDataReader.Close()
      End If

      If Not myConnection Is Nothing AndAlso ((myConnection.State And
ConnectionState.Open) = ConnectionState.Open) Then
          myConnection.Close()
      End If
   End Try
End Sub



How it works?

The above method, populates the second (child) DropDownList. cboState2 is the ID of
our second DropDownList. The third statement inside the Try block gets the reference for
the second DropDownList. Fourth and fifth statements in the Try block populates the
second DropDownList. In this example, we are setting the SelectedItemIndex for the
second DropDownList the same as the master DropDownList.

Sample output of our scenario




Fig: DataGrid with Combo Box.
Test this Script
Download the code

Click here to download the ASPX page
Click here to download the Stored Procedure

Conclusion

I have used stored procedures in all places. For your convenience, I have also included
source code for these stored procedures. If you have any questions regarding this article
or any of my article please feel free to email me at das@aspalliance.com

Links

DataGrid with Single Combo box
How to Edit a DataGrid?
How to capture a Double Click event in DataGrid?
Checkbox Web Server Control
Retrieving Images from SqlServer in ASP .NET
Retrieving Images from SqlServer and displaying it in DataGrid

Send your comments to das@aspalliance.com            Back to Article list

				
DOCUMENT INFO
Description: Asp.net complete tutorial for beginners .