In Depth ASP.NET using ADO.NET

Data Binding Button, TextBox and DropDownList cont

Binding a Button Server Control to a DataSource

Almost all user interface applications use a button, and its function is the same across every application. A button lets a user choose an option, tell the application that it is done with a task, or exit an application. The Button controls do not have a DataSource property, but we can certainly bind the attributes of the Button to fields from our data source. For example, as seen in following source code, we can bind the name of a product from our data source to the Text attribute of the Button. Here is a straightforward example of the binding a button server control to a DataSource:

<script runat="server" language="C#">
void Page_Load(Object sender, EventArgs e){
  DataBind();
}
public string ButtonText() {
  return "Click Here";
}

</script>
<html>
<body>
  <form runat="server">
  <asp:label id="message"
    runat="server"
    Font-Size="10"
  />
  <p>
    <asp:button id="Button1"
    runat="server"
    BackColor="maroon"
    ForeColor="white"
    BorderWidth="2"
    BorderStyle="Solid"
    BorderColor="Black"
    Font-Bold="true"
    Text='<%# ButtonText() %>'
    Width="200"
    />
  </p>
  </form>
</body>
</html>

Binding a TextBox Server Control to a DataSource

The TextBox server control is an input control which allows the user to enter text. By default, the TextMode property is set to SingleLine, which creates a text box with only one line. We also can set the property to MultiLine or Password. MultiLine produces a text box with more than one line. Password creates a single-line text box that masks the value entered by the user. The Columns property determines the display width of the text box. The display height is determined by the Rows property if the text box is a MultiLine text box.

We will find a sample declaration for a TextBox control in an .aspx file in the following example. The control is multiline and displays a maximum of 10 lines. If the browser supports fonts for controls, the text is formatted in Arial font. The method txtLogin_Changed is bound to the control's TextChanged method.

<asp:TextBox runat=server
    id="txtLogin"
    Text=""
    Font_Face="Arial" Font_Size="3"
    BackColor="lightblue"
    TextMode="MultiLine"
    Height="10"
    OnTextChanged="txtLogin_Changed"/>


The TextBox control also lacks a DataSource property, but we can certainly bind the attributes of the TextBox to fields from our data source. For instance, we can use a TextBox to load the initial value and then save the edited value back to our database if our site has a membership and we allow the user to edit this information. To accomplish this we can use Control.DataBind method (This binds a data source to the invoked server control and to all of its child controls):

public virtual void DataBind();

This method can be used to bind data from a source to a server control, it is commonly used after retrieving data set through a database query. When called on a server control, this method resolves all data-binding expressions in the server control and in any of its child controls. When creating custom templated databound controls this method is commonly overridden.
Let's try to use a TextBox in an aspx file. Here is a small code piece for this example:

<!-- Data Fields -->
<asp:textbox id=FirstName style="Z-INDEX: 108; LEFT: 190px; POSITION: absolute; TOP: 100px" runat="Server" width="100" height="25"></asp:textbox>

<asp:textbox id=LastName style="Z-INDEX: 109; LEFT: 190px; POSITION: absolute; TOP: 130px" runat="Server" width="100" height="25"></asp:textbox>


Just as the Windows Forms designer produces some of the most terrible code known to programmer, so does the WebForms designer. In fact, we went through and trimmed and cleaned the code for this example. After we are done with this subject, we will see more source code for this pattern. The HTML (XHTML) code for this example will be in an aspx file.

During this process the CustomerDataForm class is used and contains the page logic for such action as databinding by the application. Here is TextBox in C# code:

public class EmployeeForm : System.Web.UI.Page
{
          …
          …

  protected System.Web.UI.WebControls.TextBox LastName;
  protected System.Web.UI.WebControls.TextBox FirstName;
       
          …
          …
}


        addr.FirstName = FirstName.Text;
        addr.LastName  = LastName.Text;


((ArrayList)this.Session["Customers"]).Add( addr );
CustomerRepeater.DataSource = (ArrayList)this.Session["Customers"];
CustomerRepeater.DataBind( );

Binding a DropDownList Web Server Control

To create a single selection drop-down list control, use the DropDownList control. By setting the BorderColor, BorderStyle, and BorderWidth properties we can control the appearance of the DropDownList control. Place a ListItem element for each entry between the opening and closing tags of the DropDownList control to specify the items that we want to appear in the DropDownList control.

The DropDownList control also supports data binding. First create a data source, such as a System.Collections.ArrayList object, that contains the items to display in the control to bind the control to a data source. Next, use the Control.DataBind method to bind the data source to the DropDownList control. Now, the DropDownList control will display the information from the data source. To programmatically determine the index of the item selected by the user from the DropDownList control, use the SelectedIndex property.

DropDownList control enables users to select from a single-selection drop-down list. The drop-down portion can contain any number of list items.

<asp:DropDownList id="DropDownList1" runat="server"
    DataSource="<% databindingexpression %>"
    DataTextField="DataSourceField"
    DataValueField="DataSourceField"
    AutoPostBack="True|False"
    OnSelectedIndexChanged="OnSelectedIndexChangedMethod">
  <asp:ListItem value="value" selected="True|False">
      Text
  </asp:ListItem>
</asp:DropDownList>

The following example demonstrates how to use the DropDownList control.

<html>
<head>
  <script language="C#" runat="server">
      void Button_Click(Object sender, EventArgs e)
      {
        Label1.Text = "You selected: " +
        dropdownlist1.SelectedItem.Text + ".";       
      }
  </script>
</head>
<body>
  <form runat="server">
      <h3><font face="Verdana">DropDownList Example</font></h3>
      Select an item from the list and click the submit button.
      <p>
      <asp:DropDownList id="dropdownlist1" runat="server">
        <asp:ListItem>Item 1</asp:ListItem>
        <asp:ListItem>Item 2</asp:ListItem>
        <asp:ListItem>Item 3</asp:ListItem>
        <asp:ListItem>Item 4</asp:ListItem>
      </asp:DropDownList>
      <br><br>
      <asp:Button id="Button1" 
          Text="Submit"
          OnClick="Button_Click"
          runat="server"/>
      <br><br>
      <asp:Label id="Label1" runat="server"/>
  </form>
</body>
</html>

You might also like...

Comments

About the author

John Godel United States

John H. GODEL has an experience more than 22 years in the area of software development. He is a software engineer and architect. His interests include object-oriented and distributed computin...

Interested in writing for us? Find out more.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“God could create the world in six days because he didn't have to make it compatible with the previous version.”