Vinz' Blog

"Code, Beer and Music" ~ my way of being a programmer!
posts - 123, comments - 343, trackbacks - 0

My Links

News

Archives

Image Galleries

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..

C#

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

    sqlCmd.Parameters.AddWithValue("@username",user);
    sqlDa.Fill(dt);
    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();
    }
        connection.Close();
}

protected void Page_Load(object sender, EventArgs e)
{

   if (!Page.IsPostBack){
    getData(this.User.Identity.Name);
   }

}

VB.NET

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)
   
    sqlCmd.Parameters.AddWithValue("@username", user)
    sqlDa.Fill(dt)
    If dt.Rows.Count > 0 Then
        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()
    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;


For VB.NET
Imports System.Data;
Imports System.Data.SqlClient;

That simple! Hope this will be useful for you..

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

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 
 

Powered by: