Export (0) Print
Expand All

Data Binding Single-Value Web Server Controls at Run Time

Visual Studio .NET 2003

If you want to assign data values to a control property at run time, you can respond to a data-binding event that is raised by the control. In the event code, you can perform whatever logic is required to assign property values.

Note   At design time, you can create data-binding expressions that are evaluated at run time to assign values to control properties. For details, see Data Binding Single-Value Web Server Controls at Design Time.

To data bind single-value controls at run time

  1. Make sure that code in your Web Forms page calls the DataBind method of either the control you are working with or of the page. The data-binding event will be raised in response to this method call.
    Note   You generally do not want to call the DataBind method on each round trip (that is, in the page initialization without checking for a post back), because doing so replaces the values in controls.
  2. Create an event handler for the control's DataBinding event.
  3. In the event handler, add code to assign values to the control's properties as required.

The following example shows how to perform simple data binding at run time. The Web Forms page contains two TextBox Web server controls that display information from the titles table in the SQL Server pubs database. Previous and Next buttons set a "record position" variable that is stored in session state. Whenever the user clicks these buttons to change the record position, the page's DataBind method is called, which raises the event used to fill the text boxes.

' Visual Basic
Private Sub Page_Load(ByVal sender As System.Object, ByVal e _
   As System.EventArgs) Handles MyBase.Load
        SqlDataAdapter1.Fill(DsTitles1)
        If Not (Me.IsPostBack) Then
            Session("RecordPos") = 0
            Me.DataBind()
        End If
End Sub

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e _
   As System.EventArgs) Handles btnNext.Click
   Dim RecordPos As Integer = CType(Session("RecordPos"), Integer)
   RecordPos += 1
   If RecordPos > DsTitles1.titles.Count Then
       RecordPos -= 1
   End If
   Session("RecordPos") = RecordPos
   Me.DataBind()
End Sub

Private Sub btnPrevious_Click(ByVal sender As System.Object, ByVal e _
   As System.EventArgs) Handles btnPrevious.Click
   Dim RecordPos As Integer = CType(Session("RecordPos"), Integer)
   If RecordPos > 0 Then
       RecordPos -= 1
   End If
   Session("RecordPos") = RecordPos
   Me.DataBind()
End Sub

Private Sub TextBox1_DataBinding(ByVal sender As Object, ByVal e _
   As System.EventArgs) Handles TextBox1.DataBinding
   Dim RecordPos As Integer = CType(Session("RecordPos"), Integer)
   TextBox1.Text = DsTitles1.titles(RecordPos).title_id
   TextBox2.Text = DsTitles1.titles(RecordPos).title
End Sub

// C#
private void Page_Load(object sender, System.EventArgs e)
{
   sqlDataAdapter1.Fill(dsTitles1);
   if (!IsPostBack)
   {
Session["RecordPos"] = 0;
this.DataBind();
   }
}

private void btnNext_Click(object sender, System.EventArgs e)
{
    int RecordPos = (int) Session["RecordPos"];
    RecordPos++;
    if (RecordPos > dsTitles1.titles.Count) 
    {
        RecordPos--;
    }
    Session["RecordPos"] = RecordPos;
    this.DataBind();
}

private void btnPrevious_Click(object sender, System.EventArgs e)
{
    int RecordPos = (int) Session["RecordPos"];
    if (RecordPos > 0) 
    {
        RecordPos--;
    }
    Session["RecordPos"] = RecordPos;
    this.DataBind();
}

private void TextBox1_DataBinding(object sender, System.EventArgs e)
{
    int RecordPos = (int) Session["RecordPos"];
    TextBox1.Text = dsTitles1.titles[RecordPos].title_id;
    TextBox2.Text = dsTitles1.titles[RecordPos].title;
}

The following example binds a Label control to a value returned by executing a SQL command. The command object (which is explicitly for a SQL Server, as indicated by the named parameter) has previously been defined with a single parameter called @empid.

The user enters an employee ID and clicks a button. The button calls the Label control's DataBind method, which in turn raises the DataBinding event. In the event handler, the code gets the employee ID, sets it as a parameter for a SqlCommand object, and runs the command's SQL statement. The command returns a data reader object with one record in it, which the code reads and displays in the label.

Security Note   User input in a Web Forms page can include potentially malicious client script. By default, the Web Forms page validates that user input does not include script or HTML elements. For more information, see Scripting Exploits and Protecting Against Script Exploits in a Web Application.
' Visual Basic
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e _
   As System.EventArgs) Handles btnLogin.Click
   Label1.DataBind()
End Sub

    Private Sub Label1_DataBinding(ByVal sender As Object, ByVal e _
       As System.EventArgs) Handles Label1.DataBinding
        SqlCommand1.Parameters("@empid").Value = LoginID.Text
        SqlCommand1.CommandText = _
           "SELECT emp_id, fname, lname FROM employee WHERE (emp_id = @empid)"
        SqlCommand1.CommandType = CommandType.Text
        Dim dr As System.Data.SqlClient.SqlDataReader
        SqlConnection1.Open()
        dr = SqlCommand1.ExecuteReader()
        If dr.Read() Then
            Label1.Text = "Welcome, " & CType(dr(1), String) & " " & CType(dr(2), String)
        Else
            Label1.Text = "Login not successful."
        End If
        dr.Close()
        SqlConnection1.Close()
    End Sub

// C#
private void btnLogin_Click(object sender, System.EventArgs e)
{
   Label1.DataBind();
}

private void Label1_DataBinding(object sender, System.EventArgs e)
{
   sqlCommand1.Parameters["@empid"].Value = LoginID.Text;
   sqlCommand1.CommandText = 
      "SELECT emp_id, fname, lname FROM employee WHERE (emp_id = @empid)";   sqlCommand1.CommandType = CommandType.Text;
   System.Data.SqlClient.SqlDataReader dr;
   sqlConnection1.Open();
   dr = sqlCommand1.ExecuteReader();
   if (dr.Read())
   {
      Label1.Text = "Welcome, " + dr[1] + " " + dr[2];
   }
   else
   {
      Label1.Text = "Login not successful."
   }
   dr.Close();
   sqlConnection1.Close();
}

See Also

Introduction to Data Access in Web Forms Pages | Multi-Record and Single-Value Data Binding for Web Forms Pages | Data Binding Single-Value Web Server Controls at Design Time | Data Binding HTML Server Controls

Show:
© 2014 Microsoft