Close this search box.

Bind TextBox and Label Control with Data from database

This sample snippet below describes on how we are going to Populate a TextBox and Label control in the page based on the data associated per user using the ADO.NET way..


private void getData(string user) {
  DataTable dt = new DataTable();
  SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE");
  SqlCommand sqlCmd = new SqlCommand(
      "SELECT * from TABLE1 WHERE UserID = @username", connection);
  SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

  sqlCmd.Parameters.AddWithValue("@username", user);
  if (dt.Rows.Count > 0) {
    TextBox1.Text = dt.Rows[0]["ColumnName1"]
                        .ToString();  // Where ColumnName is the Field from the
                                      // DB that you want to display
    TextBox2.Text = dt.Rows[0]["ColumnName2"].ToString();
    Label1.Text = dt.Rows[0]["ColumnName3"].ToString();
    Label2.Text = dt.Rows[0]["ColumnName4"].ToString();

protected void Page_Load(object sender, EventArgs e) {
  if (!Page.IsPostBack) {


Private Sub getData(ByVal user As String) Dim dt As New
    DataTable() Dim connection As New
    SqlConnection("YOUR CONNECTION STRING HERE") connection
        .Open() Dim sqlCmd As New
    SqlCommand("SELECT * from TABLE1 WHERE UserID = @username",
               connection) Dim sqlDa As New SqlDataAdapter(sqlCmd)

                                       user) sqlDa.Fill(dt) If dt.Rows.Count
    > 0 Then TextBox1.Text =
        .ToString()  'Where ColumnName is the Field from the DB that you want to display TextBox2
        .Text = dt.Rows(0)("ColumnName2").ToString() Label1.Text =
        dt.Rows(0)("ColumnName3").ToString() Label2.Text =
                .ToString() End If connection
                .Close() End Sub

            Protected Sub
            Page_Load(ByVal sender As Object,
                      ByVal e As EventArgs) If Not Page.IsPostBack Then
            getData(Me.User.Identity.Name) End If End Sub

Note: Don’t forget to declare the following Namespaces below for you to make it work.

For C#:
Using System.Data;
Using System.Data.SqlClient;

Imports System.Data;
Imports System.Data.SqlClient;

That simple! Hope someone find this post useful!

Technorati Tags: ADO.NET,ASP.NET

Print | posted on Friday, September 12, 2008 1:16 AM | Filed Under 

This article is part of the GWB Archives. Original Author: Vinz

Related Posts