RSS

Search Engine

Showing posts with label ASP.NET Tutorials. Show all posts
Showing posts with label ASP.NET Tutorials. Show all posts

Thursday, May 20, 2010

ASP.Net ListBox SelectedIndex Property

The SelectedIndex property of ASP.Net ListBox control enables you to get or set the zero-based index of the selected list item dynamically using C# code. When user clicks on any list item of listbox control it fires the SelectedIndexChanged event that can be handled at server side to get the index of the list item clicked by the user. There you can use the SelectedIndex property that returns the integer type value associated to the list item selected by the user. It also allows you to set the list item at the specified index in selected state programmatically. Using SelectedIndex property in the C# code you can also access the properties of Items collection property of listbox control. Following are the properties of Items collection that can be accessed using SelectedIndex property of listbox control:

1. Attributes: it allows you to add the attributes to the associated list item dynamically.

2. Enabled: it allows you to enable or disable the selection of list item based on its Boolean type true/false value.

3. Selected: it sets the list item in selected state based on its true or false Boolean value.

4. Text: it allows you to get or set the text content of the selected list item of listbox control.

5. Value: it allows you to get or set the value of selected list item dynamically.

As SelectedIndex property is an integer type property, you can specify the integer type value to set the list item of listbox control in selected state. If you will specify the integer value more than the maximum index of listbox control items then it will throw an error: "System.ArgumentOutOfRangeException: 'ListBox1' has a SelectedIndex which is invalid because it does not exist in the list of items. Parameter name: value". Before specifying the value for SelectedIndex property you must ensure that it must be greater than or equal to 0 and less than the maximum index number of listbox control. By default the SelectedIndex property has value -1 that represents the un-selected state of all the list items of listbox.

You can use the following code to get the SelectedIndex of list item of listbox control selected by the user:

Response.Write(ListBox1.SelectedIndex);

Similarly you can assign the integer value to the SelectedIndex property to select the list item programmatically:

ListBox1.SelectedIndex = 3;

For accessing the properties of Items collection property associated to the selected list item using SelectedIndex property you can use the following

C# code:

Response.Write(ListBox1.Items[ListBox1.SelectedIndex].Value);

Similarly you can get or set the values for different properties of Items property of listbox control as we discussed earlier in this tutorial such as Attributes, Enabled, Selected, Text and Value.

ASP.Net Literal Control

The ASP.Net Literal Control provides the functionality to reserve the space on the web page to display the static text. It is similar to the ASP.Net Label control that enables you to display the text on the page. You can display the text by specifying it in the HTML source code of Literal control or programmatically by assigning the text value to its Text property using C# or VB code at server side. Unlike Label control the Literal control does not provide the inbuilt CSS based style properties to customize the look and appearance of the text displayed by it. Instead it allows you to display the plain text as well as HTML formatted text and other client side scripts. You can also display the user input on the web page by assigning that value to the Literal control programmatically. As the Literal control can render scripts also it is recommended to validate the user input before rendering it dynamically using Literal control as the user input may contain malicious scripts that could be vulnerable.

Properties of Literal Control

Following are the two main properties of the ASP.Net Literal control that enable you to control its output behavior while displaying the text on the web page dynamically:

1. Mode: It accepts the predefined enumeration values as Literal modes that enable you to control the rendering behavior of the content specified to be displayed on the web page.

2. Text: You can specify the content to the Text property of the Literal control that you want to display on the web page. The Text property can be declared either in the HTML markup code block of the Literal control or programmatically in the code behind.

Sample Code for ASP.Net Literal Control

C# Sample Code:

Literal1.Text = "Text specified dynamically.";

You can also assign the text value programmatically at page load or any event to the Text property of the Literal control as shown in the above sample code.

ASP.Net Literal Mode Property

The Mode property of ASP.Net Literal Control enables you to direct the control for customizing the rendering behavior of the specified text that you want to display on the web page. The Mode property accepts the predefined enumeration value that renders the output text according to the specified value. It enables you to display the HTML formatted text as the plain text containing encoded markup tags. You can also display the HTML formatted text as it is. The Literal control supports the dynamic rendering of text value assigned at the server side that may be retrieved from the user input. Using the Mode property you can encode the scripts before rendering them on the web page to prevent the security vulnerabilities.

ASP.Net Literal Mode Property Values

The Mode property supports the predefined set of values stored as enumeration of LiteralMode. Each value controls the Literal output in a different way to render the specified text on the web page. Following are the three types of Literal Modes:

1. Encode: It converts the specified text content to the HTML encoded string. It converts the & to & <> to >.

2. PassThrough: It does not modify the specified content and renders it by applying the HTML formatting or scripts specified in it.

3. Transform: It removes the markup tags of the unsupported markup languages when the Literal control renders on the HTML or XHTML compliance web browsers. If the specified content contains the HTML formatting then it renders the text by applying the HTML formats without modifying the content.

Sample Code for Literal Control with Mode Property

asp:Literal ID="Literal1"
runat="server"
Text="This is a literal Control.
This is a second text line."
asp:Literal


asp:Literal ID="Literal2"
runat="server"
Mode="Encode"
Text="This is a literal Control.This is a second text line."
asp:Literal


asp:Literal ID="Literal3"
runat="server"
Mode="PassThrough"
Text="This is a literal Control.This is a second text line."
asp:Literal

asp:Literal ID="Literal4"
runat="server"
Mode="Transform"
Text="This is a literal Control.
This is a second text line."
asp:Literal


In the above sample code the second Literal control we have specified the Mode as "Encode" that will convert the content to the HTML encoded content. It will not render the specified HTML formatting while rendering the content on the web page.

For the third Literal control we have specified the "PassThrough" Mode that will render the specified content by applying the HTML formats coded in the text.

In the last Literal control we have specified the Mode property value as "Transform". It will remove the unsupported markup tags from the specified text such as and . The transform mode will render the HTML formatting specified in the text without modifying its content on the web page. The "Transform" mode of the Literal control is the default behavior that will render the first Literal control also be removing the unsupported markup tag such as and but it will render the HTML
tag while generating the output.

ASP.Net Panel Control

The ASP.Net Panel control is a web server control that is rendered as div element of HTML. The div tag of HTML stands for logical division block that can hold the other controls. It serves as a container for other web server or HTML controls to provide the managed layout to the web page. The Panel control is a server control that renders on web page using the basic HTML markup code of div element. It has different types of properties that can be used to customize its appearance on web page. These properties render as attributes of div tag that renders the panel control.

Following are the properties of ASP.Net Panel Control:

BackColor: It allows you to set the background color of the panel control.

BackImageUrl: It sets the background image of the control.

BorderColor: It sets the color of the border around the panel control.

BorderStyle: You can set the style of border using this property. It supports the following predefined types of border styles:

  • Dashed
  • Dotted
  • Double
  • Groove
  • Inset
  • None
  • NotSet - It is the default value of BorderStyle property that does not render the border around the panel control.
  • Outset
  • Ridge
  • Solid

BorderWidth: It allows you to set the width of the border using CSS units such as px, pt, cm etc.

CssClass: You can specify the CSS class name for this property to apply the CSS styles to Panel control.

DefaultButton: It accepts the ID of the Button control that you want to set as default button. The default button works as the submit button for a specific group of controls whether the controls are placed inside the Panel control or web form. Specifying the ID of the Button control to the DefaultButton property of Panel control executes the associated server side event of that button when user hits the enter key from the keyboard.

Direction: It accepts one of the predefined keyword values that sets the direction of the text placed inside the Panel control. It supports the following predefined values:

  • NotSet - default value.
  • LeftToRight
  • RightToLeft

Font-properties: The font property group contains following set of properties which allow you to change appearance of text placed inside the Panel.

  • Font-Bold
  • Font-Italics
  • Font-Names
  • Font-Overline
  • Font-Size
  • Font-Strikeout
  • Font-Underline

ForeColor: It allows you to set the font color of the text.

GroupingText: It renders the group box with a text at top left corner inside the Panel control. The group box is being rendered by fieldset and legend HTML elements that display the bordered group box with a caption text.

HorizontalAlign: It sets the horizontal alignment of the text placed inside the Panel control.

Height: It sets height of the control.

Scrollbars: It enables you to display the scrollbars for the Panel control. You can control the appearance of scrollbars by specifying one of the predefined values for this property:

  • None
  • Horizontal
  • Vertical
  • Both
  • Auto

This property sets the CSS overflow property value for the div tag that generates the panel control on the web page.

Width: It sets the width of the control.

Wrap: It allows to enable or disable the text wrapping.

You can also customize the look of ASP.Net Panel control using inline style attribute by specifying the CSS properties in the HTML markup code block.

Sample Code for ASP.Net Panel Control

asp:Panel ID="Panel1"
runat="server"
Style="border: solid 1px #c0c0c0; width: 300px;
height: 300px; float: left"
GroupingText="Login"


Continue to the next tutorial: ASP.Net PlaceHolder control that provides the functionality to render as invisible container on the web page just as a server side place holder which allows you to add the ASP.Net controls dynamically.

Wednesday, May 19, 2010

ASP.Net PlaceHolder Control

The ASP.Net PlaceHolder control provides the functionality to reserve a location on ASP.Net web page that can be further used for adding child controls dynamically. You can change the control hierarchy of web page using this amazing PlaceHolder control that enables you to add and render the ASP.Net server controls dynamically at the runtime. The ASP.Net PlaceHolder control does appear as a physical element on the web page when it loads. Instead it holds a particular location on the page that expands to adjust the new child control added dynamically into it. You can add a single or multiple controls as a collection of controls to the PlaceHolder control. The Controls collection property of PlaceHolder control provides access to the methods such as Add, AddAt, Remove, RemoveAt, Clear etc. These methods allow you to add or remove the controls dynamically.

Sample Code for ASP.Net PlaceHolder Control

asp:PlaceHolder ID="PlaceHolder1" runat="server"
asp:PlaceHolder

If you will add the above HTML markup code of PlaceHolder control in the web page it will not display any output control in the browser window. Even if you will try to view the page source code, there will be no HTML element associated to it. The ASP.Net Panel control that we discussed in the previous tutorial also provides the functionality to add the server controls dynamically. You can also customize the appearance of Panel control using CSS styles that renders as HTML div element whereas PlaceHolder control does not renders with visible boundaries or HTML element.

ASP.Net RadioButton Control

The ASP.Net RadioButton control provides the functionality to display an individual radio button on the Web form that returns the true or false type Boolean value as a result. If the RadioButton control is in selected state then it returns true and if it is in unselected state then the radio button returns false. You can display a group of multiple radio buttons on the web page to provide a mutually exclusive set of options to the users. Users can select one of the radio buttons from the group to specify their choice. You can perform the server side action based on the selection made by the user that can detected by getting the value of checked property of each radio button displayed as a member of the group.

Properties of ASP.Net RadioButton Control

Following are the properties of ASP.Net RadioButton control to get or set its value or behavior on the web page:

1. Checked: It gets or sets the radiobutton state. If the radio button control is in selected state then checked property returns true otherwise it returns false. The Checked property of radio button control accepts and returns Boolean value.

2. AutoPostBack: If you want to execute the PostBack event of radio button control when user changes its state to selected state. The AutoPostBack property also accepts the Boolean value i.e. true or false to allow or disallow the PostBack event of radio button control.

3. GroupName: It accepts the string value as a name for the group of radio buttons to create a list of mutually exclusive set of options. Multiple radio buttons specified with same GroupName allows to select only one radio button option.

4. Text: It allows you to display the label with a text string next to the radiobutton control. You can specify a string value for the text property of radio button control.

5. TextAlign: It enables you to adjust the alignment of the text value specifvied to the Text property of the radio button. You can align the specified text to the left or right side of the radio button.

The RadioButton control consists of following PostBack event that can be handled at server side to execute the server code and perform the speciifed action according to the selected radio button control:

CheckedChanged Event: It enables you to handle the PostBack event of radiobutton control when user changes its state from selected state. When user clicks the radio button it raises the CheckedChanged event only if the AutoPostBack property of RadioButton control is set to true.

The radio button control is an ASP.Net web server control when it is rendered on the web page it splits up into two parts:

1. HTML input control having "type" attribute value as "radio".

2. HTML label control to display the string specified for the text property of radio button server control.

ASP.Net RadioButton Checked And GroupName Property

The Checked property of ASP.Net RadioButton control enables you to get or set the selected state of radiobutton. You can also set the checked property of radio button control dynamically using server code or manually when user clicks the radiobutton control to change its selected state. The checked property of ASP.Net radiobutton control accepts the Boolean value to set its state. It also returns the Boolean value to represent the state of the radio button placed on the web page. When user clicks the radiobutton control to set its state as checked then it returns "true" and when user selects other radio button from the same group then it sets the first radio button to un-checked state and clicked radio button to checked state.

Sample Code for ASP.Net RadioButton Checked Property

source code for RadioButton control we have declared the Checked property as "true" for the first radio button. It will render the radio button with checked state initially. To create the mutually exclusive set of choices we have used the GroupName property of radio buttons assigned with same value as "group1". It will provide the functionality to select the single radio button within the same group of radio buttons.

C# Code:

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "RadioButton1.Checked = " + RadioButton1.Checked.ToString() + "
";
Label1.Text += "RadioButton2.Checked = " + RadioButton2.Checked.ToString();
}

We have also used the Button Control to get the value of Checked property of radio button controls. In the attached click event handler of Button control we have retrieved the values to display them on the web page with the help of Label control.

ASP.Net RadioButton AutoPostback Property

The AutoPostBack property of the ASP.Net RadioButton control provides the functionality to allow the server side post back event of the web page when user clicks the radio button to change its inactive state to selected state. You can get the value of checked state of the radio button control at the Page Load event of ASP.Net web page to perform the server side action based on the checked state of radio button. The AutoPostBack property is a Boolean type property that accepts value as true/false to enable or disable the auto post back functionality of the radio button control to the server side when user selects it. You can declare its value in two ways such as in HTML code block as an inline attribute of radio button control or by declaring it programmatically when page loads.

Sample Code for ASP.Net RadioButton AutoPostBack Property

we have used 2 ASP.Net radio button controls declared with their GroupName property and AutoPostBack property. The GoupName property enables you to create a group of radio buttons so that the user could select only one radio button among multiple set of options. The AutoPostBack property is used in the sample to allow the controls for posting the web form data to the server when user will click any of the radio button control. Other than the radio button controls we have used ASP.Net Panel controls also to illustrate the additional functionality that can be provided along with the AutoPostBack feature of radio button controls. When the user will select the first radio button then it will set the first panel control to be visible on the web page where as the second radio button will hide the first panel control and display the second panel control associated to it.

C# Code:

protected void Page_Load(object sender, EventArgs e)
{
Panel1.Visible = RadioButton1.Checked;
Panel2.Visible = !RadioButton1.Checked;
}

The C# code shows that you can get the value of checked property of radio button controls at the Page Load event of ASP.Net web page when the AutoPostBack property of radio button controls is specified with value "true".

ASP.Net RadioButton OnCheckedChanged Event

The OnCheckedChanged event handler of ASP.Net RadioButton control enables you to handle the click event of radio button at server side that is raised at the time when user clicks the control to change its in-active state. The CheckedChanged event of radio button control occurs only if its AutoPostBack property is specified with value "true". You can handle the click events of multiple radio button controls separately and perform the server side action for each control using their dedicate OnCheckedChaneged event handlers. The CheckedChanged event occurs immediately when user clicks the radio button control for selecting the item and submits the web form to the server only if the AutoPostBack property has value "true".

Sample Code for ASP.Net RadioButton OnCheckedChanged Event

we have used two radio buttons specified with their AutoPostBack property value as "true" and also OnCheckedChanged server side event is used to handle the click event of each radio button separately when user clicks the control to change its checked state.

You can attach the CheckedEvent of radio button control in two ways as follows:

1. Double clicking the radio button control for which you want to generate the server side OnCheckedChanged event handler. In this tutorial we have also used the same approach to handle the CheckedChanged event of radio buttons.

2. You can also attach the CheckedChanged event programmatically in the page load method of ASP.Net web page E.g.:

protected void Page_Load(object sender, EventArgs e)
{
RadioButton1.CheckedChanged += new EventHandler(RadioButton1_CheckedChanged);
}

void RadioButton1_CheckedChanged (object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}

When you will write the ID of the radio button control inside the Page_Load method for example RadioButton1, and will type the "." Dot operator it will display the list of properties and methods of radiobutton control. Select the CheckedChanged event from the intellisense and press "+=" and then tab key from the keyboard. It will generate the event handler automatically.

C# code:

protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
Panel1.Visible = RadioButton1.Checked;
Panel2.Visible = !RadioButton1.Checked;
}

protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
Panel1.Visible = !RadioButton2.Checked;
Panel2.Visible = RadioButton2.Checked;
}

The above server side event handlers will handle the checked changed event of both radio button controls individually that we placed on the web page as discussed above. Other than radio button controls we have used two ASP.Net Panel controls also to illustrate the additional functionality that you can combine with the checked changed event of radio button controls. When you will click the first radio button then it will hide the second panel control and will display only first Panel control as an associated control to it. Whereas when you will click the second radio button control then its CheckedChanged handler code will execute and will set the visible state of the second panel control to true and first panel control to false.

Tuesday, May 18, 2010

ASP.Net RadioButtonList Control

The ASP.Net RadioButtonList control provides the functionality to display radio button controls as ListItems in the Web form. You can select the one radio button item of RadioButtonList control by changing the inactive state of the selected item. The selected item of RadioButtonList returns the Boolean type result as true or false that determines the checked state of an individual list item based on the C# code logic applied on it. If the list item is in checked state then it returns true and if it is in unchecked state then the radio button rendered as list item returns false. You can use the ASP.Net RadioButtonList web server control to get the user input as a single selection under a specific group of multiple multually exclusive options. Some simple examples of RadioButtonList control are displaying a list of titles prefixes for name such as "Mr", "Ms", "Er" or "Dr." etc. Users can select only one Title as their Name prefix. Similarly you can display the gender options using RadioButtonList control such as "Male" or "Female" and user can choose one. The ASP.Net RadioButtonList control provides the inbuilt functionality to display the radio button list items as multually exclusive set of choices that allow the users to select only one item among the multiple options.

The ASP.Net RadioButtonList control consists of following properties that are commonly used to get or set the values or user input. There are two sets of properties below; the first set includes the properties that enable you to get or set the values of list items of RadioButtonList and the second set includes the properties that enable you to customize its appearance:

AppendDataBoundItems: It allows you to add the list items of RadioButtonList statically along with the data-bound list items retrieved from any data source. It is a Boolean type property that accepts value as true or false for allowing or disallowing the append feature of list items.

AutoPostBack: It is also a Boolean type property that enables the control to send the web page to PostBack when user clicks the radio button list item to select it.

DataMember: It accepts the name of one of the data table stored in the data source, if there is a collection of data tables in it. For example using SQL queries or stored procedures you can retrieve data in the form of multiple data tables that can be stored into the DataSet class object. This DataSet object can be used to bind the data to different types of Data-bound controls. The DataMember property enables you to specify the name of the table that you want to bind with the data-bound control.

DataSource: This property allows you to specify the name of the data source dynamically.

DataSourceID: It accepts the ID of the DataSource control used to retrieve the data from the database.

DataTextField: It accepts the name of the Field/Column of the data table stored in the datasource object that you want to display as the text content of the list item.

DataTextFormatString: It allows you to format the text property of the RadioButtonList item. For example you can use {0:C} to format the numeric value as currency. There are different types of formats such as {0:X}, {0:E}, {0:N}, {0:C}. You can learn about these formats from this tutorial: ASP.Net C# String Format Function

DataValueField: It accepts the name of the field of the data table stored in the datasource object that you want to set as the value attribute of each list item. This value part does not appear as text content.

Layout Properties of ASP.Net RadioButtonList Control

The ASP.Net RadioButtonList control also consists of CSS styles based properties and Layout properties that allow you to change the appearance and rendering behavior of the control. You can change the background color of the control, set the border around the control along with its border color. You can specify the style of the border and its width using CSS units to display the bordered edges of RadioButtonList control. It also provides the properties to customize the font style to display the text content of the list items of the control. You can also use the CSS class styles to customize the look and feel as well as layout of the radiobuttonlist control.

The Layout properties of RadioButtonList control include the following 3 properties:

RepeatColumns: It accepts the integer value that renders the layout of the radiobuttonlist control with specified number of columns. 0 is the default value of RepeatColumns property that renders the list items as a single vertical list of radio button items.

RepeatDirection: It allows you to set the rendering direction of list items of the radiobuttonlist control. RepeatDirection property accepts one of the following predefined values:

1. Horizontal: this value renders the list items in left to right manner. Each item renders at the right side of the previous until it reaches the specified number of RepeatColumns property value. Then it renders the next item in new line or row of the table based on the RepeatLayout property value.

2. Vertical: this value renders the list items in top to bottom manner. Each items renders below the previous item in a new row cell each time. It applies some logic to render the vertical layout of the radiobuttonlist items.

RepeatLayout: It enables you to specify the layout type of the radiobuttonlist control. You can specify the RepeatLayout property using any one of the following predefined keywords:

1. Table: It renders the list items using HTML table element. It generates the table cells and rows to display the radiobuttonlist items using table layout.

2. Flow: It renders the list items using HTML span element as a container and it uses the HTML
tag to enter the line break between the radio button list items to generate new rows.

"Table" is the default value of RepeatLayout property.

Following is a list of CSS based properties of the ASP.Net RadioButtonList control that can be used to customize its look and feel:

BackColor: allows you to set the background color.

BorderColor: allows you to set the border color.

BorderStyle: allows you to set the predefined style of the border around the radiobuttonlist. You can specify the border styles such as solid, dotted, dashed etc.

BorderWidth: allows you to set the width of the border using CSS units such as px, pt, cm etc.

CellPadding: It sets the cell padding for the table cells of the radiobuttonlist control when rendered with RepeatLayout property as "Table".

CellSpacing: It sets the cell spacing for the table cells of the radiobuttonlist control when rendered with RepeatLayout property as "Table".

CssClass: allows you to specify the name of the CSS class to customize the look and feel of radiobuttonlist control.

Font Style Properties: the font style properties of radiobuttonlist include font-size, family, bold, italics etc.

ForeColor: Sets the color of the text content of the listitems

TextAlign: It enables you to set the horizontal alignment of the text aligned to left or right direction.

ASP.Net RadioButtonList OnSelectedIndexChanged Event

The OnSelectedIndexChanged event handler of ASP.Net RadioButtonList control enables you to handle the click event of radiobuttonlist item at server side that is raised at the time when user clicks the radio button list list item to change its inactive state to selected/checked state. The SelectedIndexChanged event of RadioButtonList control occurs only if the AutoPostBack property of radiobuttonlist is specified with value "true". The SelectedIndexChanged event occurs immediately when the checked state of the list item of radiobuttonlist changes and it submits the web form to the server only if the AutoPostBack property has value "true". You can handle the event at server side using C# code and apply the custom logic there to execute any specific action.

Sample Code for ASP.Net RadioButtonList OnSelectedIndexChanged Event

In the above sample code for RadioButtonList control we have specified the AutoPostBack property value as "true" and also OnSelectedIndexChanged server side event is used to handle the click event of radiobutton list item when user clicks the control to change its checked state.

You can attach the SelectedIndexChanged of RadioButtonList control in two ways as follows:

1. Double clicking the RadioButtonList control for which you want to generate the server side OnSelectedIndexChanged event handler. In this tutorial we have also used the same approach to handle the SelectedIndexChanged event of RadioButtonList control.

2. You can also attach the SelectedIndexChanged event programmatically in the page load method of ASP.Net web page E.g.:

protected void Page_Load(object sender, EventArgs e)
{
RadioButtonList1.SelectedIndexChanged += new EventHandler(RadioButtonList1_SelectedIndexChanged);
}

void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
throw new Exception("The method or operation is not implemented.");
}

When you will write the ID of the radiobuttonlist control inside the Page_Load method for example RadioButtonList1, and will type the "." Dot operator it will display the list of properties and methods of radiobuttonlist control. Select the SelectedIndexChanged event from the intellisense and press "+=" and then tab key from the keyboard. It will generate the event handler automatically.

C# code:

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
Label1.Text = "Selected Index: " + RadioButtonList1.SelectedIndex.ToString() + "
";
Label1.Text += "Selected Value: " + RadioButtonList1.SelectedValue + "";
}

In the above C# sample code for SelectIndexChanged event handler of ASP.Net RadioButtonList control we have retrieved the values of its two properties such as SelectedIndex and SelectedValue. The SelectedIndex property of RadioButtonList control returns the index of the list item clicked by the user where as SelectedValue property returns the value of the selected radio button type list item of the radiobuttonlist control.

ASP.Net RadioButtonList Control with SQL DataBinding

The ASP.Net RadioButtonList control also supports SQL DataBinding feature that enables you to display the data retrieved from the SQL Database in the form of radio button type list items. You can either use the SqlDataSource control to bind the SQL data with radiobuttonlist control or C# code to bind the data programmatically. Using SqlDataSource control you can bind data items with radiobuttonlist control without writing any single line of C# code. You can display the data items by specifying the ID of the SqlDataSource control as a value of DataSourceID property of the RadioButtonList control. While using C# code to bind the SQL data dynamically you have to use the DataSource property of radiobuttonlist control to bind the data object.

But specifying only DataSourceID or DataSource property of ASP.Net RadioButtonList control is not enough. You have to specify the values for 2 more properties to display the text content of radiobutton list items and set the value for each list item. Following are the two properties that enable you to specify the text and value property of list items of RadioButtonList control:

DataTextField: It accepts the name of the Field of the data table retrieved using datasource control or data access C# code that you want to display as the text content of the list item.

DataValueField: It accepts the name of the field of the data table retrieved using datasource control or data access C# code that you want to set as the value attribute of each list item. This value part does not appear as text content.

Sample Code for ASP.Net RadioButtonList SQL DataBinding

C# Code:

public void BindRadioButtonListData()
{
// connection string
string connectionString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

// Sql connection object initialized with connection string used to connect
// it with Northwind SQL database
using (SqlConnection mySqlConnection = new SqlConnection(connectionString))
{
try
{
// open the Sql connection
mySqlConnection.Open();

// Sql Command object initialized with SQL query to retrieve the categories
SqlCommand mySqlCommand = new SqlCommand("Select CategoryID, CategoryName from Categories", mySqlConnection);

// Sql Data Adapter object initialized by passing the Sql Command object
SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(mySqlCommand);


// DataSet object to store the retrieved SQL data items
DataSet myDataSet = new DataSet();

// fill the DataSet
mySqlDataAdapter.Fill(myDataSet);

// Set DataSet object as DataSource for the RadioButtonList
RadioButtonList1.DataSource = myDataSet;

// Specify the Field Name that you want to display as
// text label for Radio Button list item
RadioButtonList1.DataTextField = "CategoryName";

// Specify the Field Name that you want to use as
// value for each list item
RadioButtonList1.DataValueField = "CategoryID";

// Finalize the DataBinding
RadioButtonList1.DataBind();

}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
finally
{
// close the Sql Connection
mySqlConnection.Close();
}
}
}

You can call the above function in the Page load event of the ASP.Net web page to bind the SQL data with RadioButtonList control.

Populating the ASP.Net RadioButtonList Control Items Dynamically

The ASP.Net RadioButtonList control also provides the method to populate it by adding the list items dynamically using C# code. You can use the Add method of Items collection property of RadioButtonList control to populate the items programmatically. The Items property gets the collection of list items stored in the RadioButtonList control. It belongs to the ListItemCollection class and provides the read-only member of this collection class. The Items property further enables you to access the public methods of ListItemCollection class that allow you to add or remove the list items. Here we will use the Add method to populate the list items into the RadioButtonList control.

Following are the two overloaded ways of using the Add method of Items collection property of RadioButtonList:

1. [RadioButtonList].Items.Add( ListItem item );

It allows you to add the specified list item at the end of RadioButtonList collection. You can use the well suited overloaded way of ListItem class constructor to add a new item.

2. [RadioButtonList].Items.Add( string text );

It appends the collection of list items of RadioButtonList control by adding the specified string at the end of collection.

For adding the ListItem using first overloaded Add method you can use the following overloaded constructor of ListItem class:

new ListItem( string text, string value );

It allows you to add the ListItem with its text that will appear in the RadioButtonList control along with its value that will work at the back end.

Sample Code to Populate RadioButtonList Control Dynamically

HTML Code:


C# Code:

There are different ways to add the List Items into the RadioButtonList control. In the following samples we have shown 2 different ways to add the ListItems:

Example 1:

ListItemCollection itemsCollection = RadioButtonList2.Items;

itemsCollection.Add(new ListItem("item 1", "1"));

itemsCollection.Add(new ListItem("item 2", "2"));

itemsCollection.Add(new ListItem("item 3", "3"));

itemsCollection.Add(new ListItem("item 4", "4"));

itemsCollection.Add(new ListItem("item 5", "5"));

Example 2:

RadioButtonList2.Items.Add(new ListItem("item 1", "1"));

RadioButtonList2.Items.Add(new ListItem("item 2", "2"));

RadioButtonList2.Items.Add(new ListItem("item 3", "3"));

RadioButtonList2.Items.Add(new ListItem("item 4", "4"));

RadioButtonList2.Items.Add(new ListItem("item 5", "5"));

You can build your logic to add the ListItems into the ListItemCollection of RadioButtonList control using any of the above C# code. You can also use C# for loop to add the items that will also reduce the code lines.

ASP.Net TextBox Control

The ASP.Net TextBox control enables you to display an input type textbox control on the ASP.net web page that allows the users to enter their input in text mode and submit it to the server side using ASP.Net Button control. You can get or set the value to or from the ASP.Net Textbox control using its Text property programmatically. It support both plain text as well as HTML code or scripts that can be submitted to the server side or can be displayed in the multiline enabled textbox control. The HTML code and CSS support of textbox control enables you to customize the styles of the text entered through it. This feature also leads to security vulnerabilities. That is why it is recommended to validate the input entered by the user into the ASP.Net textbox control to prevent the execution of malicious client side scripts. You can also attach the client side events to the textbox control that can be used to validate the user input.

Properties of ASP.Net TextBox Control

The TextBox control consists of two types of properties such as CSS based style properties that allow you to customize the look and feel of the control as well as the input text entered by the users and the other type of properties handles the behavior of textbox.

Following are the commonly used properties of ASP.Net Textbox control:

1. AutoCompleteType: It accepts the predefined keyword for example FirstName, LastName, Email etc. that provides the functionality to display the autocomplete list under the textbox control to enter the input from the previously entered values for the textboxes with same AutoCompleteType.

2. AutoPostBack: It is a Boolean type property that enables or disables the auto postback functionality of text box control that posts the web page to server when user enters the input into the textbox control jumps to the another control.

3. CausesValidation: It is also a Boolean type property that enables or disables the validation controls associated with the textbox control to validate the input.

4. Columns: It accepts the integer value to set the width of the multiline textbox. The integer value enables the control to accommodate the specified number of characters horizontally.

5. MaxLength: It also accepts the integer value that restricts the control to reject the characters exceeding the specified value. This property works with single line textbox control

6. ReadOnly: It is a Boolean property that enables or disables the textbox control whether to allow the user to change its value or not.

7. Rows: It accepts the integer value to set the height of the multiline textbox. The integer value enables the control to accommodate the specified number of characters vertically.

8. Text: It accepts the text value that you want to display in the textbox control initially. You can assign the value dynamically as well as get the value entered by the user through the Text property of ASP.Net textbox control.

9. TextMode: It accepts the predefined keyword such as SingleLine, MultiLine or Password that adjusts the behavior of the textbox control on the web page.

10. ValidationGroup: It accepts the name of the validation group to which it belongs that validates the user input when a postback occurs.

Other than the above properties it also contains CSS based properties that allow you to customize the style of the textbox and the input text. These properties include BackColor, BorderColor, BorderStyle, BorderWidth, CssClass, Font-Bold, Font-Italic, Font-Names, Font-Overline, Font-Size, Font-StrikeOut, Font-Underline, ForeColor, Height and Width.

ASP.Net TextBox Events

The textbox control provides OnTextChanged event that can be used to read and validate the user input entered into the textbox.

Monday, May 17, 2010

ASP.Net TextBox Control OnTextChanged event

The ASP.Net TextBox control provides OnTextChanged event that enables you to get the input value entered by the user immediately after when he leaves the textbox control. The textbox control raises the TextChanged event when user jumps to another control on the web page after filling the information in the textbox control. It does not raise any event for each keystroke made by the user it occurs only when the user leaves the associated textbox control. You can handle the OnTextChanged event at server side that can be used to get the textbox value and validate it before submitting to the data store or further processing.

There are two different types of behaviors of OnTextChanged event of ASP.Net TextBox control that are based on the value of its AutoPostBack property as follow:

1. By default the AutoPostBack property value is false that does not allow the TextBox control to raise the TextChanged event immediately after the user leaves the control. It fires the event and executes the server side OnTextChanged handler code at the time the form is posted to the server.

2. The second type of behavior is executing the TextChanged event immediately when user leaves the textbox control that posts the web form to the server. This instant behavior can be set by setting the AutoPostBack property of textbox control to true.

Attaching the OnTextChanged Event to ASP.Net TextBox

You can attach the TextChanged event of textbox control in two ways as follows:

1. Double clicking the textbox control for which you want to generate the server side OnTextChanged event handler. In this tutorial we have also used the same approach to handle the TextChanged event of textbox control.

2. You can also attach the TextChanged event programmatically in the page load method of ASP.Net web page E.g.:

protected void Page_Load(object sender, EventArgs e)
{
TextBox1.TextChanged += new EventHandler(TextBox1_TextChanged);
}

void TextBox1_TextChanged(object sender, EventArgs e)
{

}

When you will write the ID of the textbox control inside the Page_Load method for example TextBox1, and will type the "." Dot operator it will display the list of properties and methods of textbox control. Select the TextChanged event from the intellisense and press "+=" and then tab key from the keyboard. It will generate the event handler server side code automatically.

Example of TextChanged Event

C# Code:

protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label1.Text += "TextChanged event: " + TextBox1.Text;
Label1.Text += "
";
}

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text += "Click event: " + TextBox1.Text;
}

In the above example we have used the default behavior of OnTextChanged event of ASP.Net Textbox control that executes at the time when the web form is posted to the server. When user will enter the input to the textbox control and click the button control it will first raise the TextChanged event and then Click event of button control.

ASP.Net XML Control

The ASP.Net XML Control is an inbuilt web server control that is used to display as XML document on the ASP.Net web page. It provides the functionality to parse the XML document and transform its contents using XSL Transform. Here XSL stands for Extensible StyleSheet Language that provides the functionality to transform the XML document into the desired format such as HTML or XHTML. The ASP.Net XML control consists of properties that accept the paths to the XML document and XSL Transform to display the XML content transformed into the HTML or XHTML format.

Properties of ASP.Net XML Control

You can transform the XML document using XML control in two ways, first is by using inline properties of ASP.Net XML control and second by assigning the objects programmatically.

Inline Properties of XML Control

1. DocumentSource: It accepts string value as a path to the XML document file that is to be displayed on an ASP.Net web page.

2. TransformSource: It also accepts string value as a path to the XSL Transformation file that transforms the specified xml file into HTML format.

Dynamic Objects of XML Control

1. Document: This object type has been deprecated for future use. It provides the XML document object as System.Xml.XmlDocument class object that is to be displayed on the web page using ASP.Net XML control.

2. Transform: It gets or sets the System.Xml.Xsl.XslTransform class object that formats the XML document before writing it to the output stream.

ASP.Net Markup Tag for Xml Control


Sunday, May 16, 2010

ASP.Net XML Control Example with Document and Transform Properties

In this tutorial we will learn how to transform an XML document using Document and Transform property of ASP.Net XML control programmatically. You can load the XML document into the Document object and XSL file into the Transform object that enable you to format the XML document before writing it to the output stream. In the previous tutorial we learnt how to parse the XML content into the HTML format using inline DocumentSource and TransformSource properties of XML control but here we will use the C# code to create the XmlDocument object and XslTransform object to load and transform the provided Xml file. Let's take a look at short descriptions of Document and Transform properties to learn their implementation:

1. Document: It accepts the System.Xml.XmlDocument class object loaded with valid XML document that is to be displayed on web page using ASP.Net XML Control.

2. Transform: It accepts the System.Xml.Xsl.XslTransform class object loaded with valid Xsl Transformation style to parse the specified XML document into the desired HTML format.

If you will not pass the transform object to the XML control's Transform property then it writes the unformatted XML document content on the web page.

Example for ASP.Net XML control

HTML Code:

C# Code:

protected void Page_Load(object sender, EventArgs e)
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(Server.MapPath("books.xml"));

XslTransform xslTransform = new XslTransform();
xslTransform.Load(Server.MapPath("CatalogFilter.xslt"));

Xml1.Document = xmlDocument;
Xml1.Transform = xslTransform;
}

To use the XmlDocument class and XslTransform class in your code behind you need to import the following Namespaces:

using System.Xml;
using System.Xml.Xsl;

The System.Xml namespace provides the access to the XmlDocument class and System.Xml.Xsl namespace enables you to use the XslTransform class. In the above sample code we have used the Server.MapPath method to specify and load the Xml document and Xsl file to their respective XmlDocument object and XslTransform object. Further we have set the Document and Transform properties of ASP.Net XML control dynamically. It will transform the specified XML file into the HTML format provided in the XSL transformation style sheet loaded in the transform class object.

You can use the XML file and XSL file that we used in the previous tutorial: ASP.Net XML Control Example with DocumentSource and TransformSource Properties.

What Are Active Server Pages?

What Are Active Server Pages?

Active Server Pages (ASPs) are Web pages that contain server-side scripts in addition to the usual mixture of text and HTML (Hypertext Markup Language) tags. Server-side scripts are special commands you put in Web pages that are processed before the pages are sent from your Personal Web Server to the Web browser of someone who's visiting your Web site. . When you type a URL in the Address box or click a link on a Web page, you're asking a Web server on a computer somewhere to send a file to the Web browser (sometimes called a "client") on your computer. If that file is a normal HTML file, it looks exactly the same when your Web browser receives it as it did before the Web server sent it. After receiving the file, your Web browser displays its contents as a combination of text, images, and sounds.

In the case of an Active Server Page, the process is similar, except there's an extra processing step that takes place just before the Web server sends the file. Before the Web server sends the Active Server Page to the Web browser, it runs all server-side scripts contained in the page. Some of these scripts display the current date, time, and other information. Others process information the user has just typed into a form, such as a page in the Web site's guestbook.

To distinguish them from normal HTML pages, Active Server Pages are given the ".asp" extension.

What Can You Do with Active Server Pages?

There are many things you can do with Active Server Pages.
  • You can display date, time, and other information in different ways.
  • You can make a survey form and ask people who visit your site to fill it out, send emails, save the information to a file, etc

What Do Active Server Pages Look Like?

The appearance of an Active Server Page depends on who or what is viewing it. To the Web browser that receives it, an Active Server Page looks just like a normal HTML page. If a visitor to your Web site views the source code of an Active Server Page, that's what they see: a normal HTML page. However, the file located in the server looks very different. In addition to text and HTML tags, you also see server-side scripts. This is what the Active Server Page looks like to the Web server before it is processed and sent in response to a request.

What Do Server-Side Scripts Look Like?

Server-side scripts look a lot like HTML tags. However, instead of starting and ending with lesser-than ( < ) and greater-than ( > ) brackets, they typically start with <% and end with %>. The <% is called an opening tag, and the %> is called a closing tag. In between these tags are the server-side scripts. You can insert server-side scripts anywhere in your Web page--even inside HTML tags.

Do You Have to Be a Programmer to Understand Server-Side Scripting?

There's a lot you can do with server-side scripts without learning how to program. For this reason, much of the online Help for Active Server Pages is written for people who are familiar with HTML but aren't computer programmers.

Friday, May 14, 2010

ASP.NET vs. ASP

ASP.NET has better language support, a large set of new controls, XML-based components, and better user authentication.

ASP.NET provides increased performance by running compiled code.

ASP.NET code is not fully backward compatible with ASP.


New in ASP.NET

  • Better language support
  • Programmable controls
  • Event-driven programming
  • XML-based components
  • User authentication, with accounts and roles
  • Higher scalability
  • Increased performance - Compiled code
  • Easier configuration and deployment
  • Not fully ASP compatible

Language Support

ASP.NET uses ADO.NET.

ASP.NET supports full Visual Basic, not VBScript.

ASP.NET supports C# (C sharp) and C++.

ASP.NET supports JScript.


ASP.NET Controls

ASP.NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined as ASP.NET control objects that can be controlled by scripts.

ASP.NET also contains a new set of object-oriented input controls, like programmable list-boxes and validation controls.

A new data grid control supports sorting, data paging, and everything you can expect from a dataset control.


Event Aware Controls

All ASP.NET objects on a Web page can expose events that can be processed by ASP.NET code.

Load, Click and Change events handled by code makes coding much simpler and much better organized.


ASP.NET Components

ASP.NET components are heavily based on XML. Like the new AD Rotator, that uses XML to store advertisement information and configuration.


User Authentication

ASP.NET supports form-based user authentication, cookie management, and automatic redirecting of unauthorized logins.


User Accounts and Roles

ASP.NET allows user accounts and roles, to give each user (with a given role) access to different server code and executables.


High Scalability

Much has been done with ASP.NET to provide greater scalability.

Server-to-server communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers.


Compiled Code

The first request for an ASP.NET page on the server will compile the ASP.NET code and keep a cached copy in memory. The result of this is greatly increased performance.


Easy Configuration

Configuration of ASP.NET is done with plain text files.

Configuration files can be uploaded or changed while the application is running. No need to restart the server. No more metabase or registry puzzle.


Easy Deployment

No more server-restart to deploy or replace compiled code. ASP.NET simply redirects all new requests to the new code.


Compatibility

ASP.NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP.NET.

To overcome this problem, ASP.NET uses a new file extension ".aspx". This will make ASP.NET applications able to run side by side with standard ASP applications on the same server.