War On Errors Sign In
Article ID: 31403
Last Reviewed: 4/17/2010 11:42:50 PM

Bind an ASPNET Textbox to an SqlDatasource programmatically

Problem

You will often find that you may need to bind an asp:sqldatasource to a control on an aspx page. Some controls like the asp:dropdownlist have attributes that allow you to do this easily. Unfortunately, binding to an asp:sqldatasource in other controls, including asp:Textbox, is not as obvious. One way to accomplish this task is to use the codebehind to programmatically bind the data.

Resolution

For this example we'll say that we only want to retrieve one column called AccountName from our SQL database. 

1.) First thing to do is create the textbox :

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

Note: Whenever you want to access a control's parameters from codebehind, you must include the runat="server" within the opening tag of the control.


2.) Next, we create the asp:sqldatasource:

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"

SelectCommand="SELECT * FROM [Accounts]" >

</asp:SqlDataSource>

 


3.) Finally, We add the codebehind.  In this case we'll just use the PageLoad event. 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

         Dim dv As DataView = DirectCast(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)

        For Each drv As DataRowView In dv

            TextBox1.Text = drvSql("AccountName").ToString()

        '   Add as many textboxes or labels as you need

        Next

End Sub

 


That's it! 

You can use this technique with any control you see fit just as long as you include the runat="server" in the opening tag. 


Keywords:
asp:TextBox SqlDataSource1 access a control's parameters from codebehind SqlDatasource programmatically Bind an ASPNET Textbox