Categories
Asp, Asp.net

How To Bind Data To Textbox and Label In ASP.NET

How To Bind Data To Textbox and Label In ASP.NET

In this post i will explain you How To Bind Data To Textbox and Label In ASP.NET.Here i am using SQL Server as backend from where i am fetching data and then binding that data into Textbox and Label.

Design View:-

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
    <tr>
    <td>
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label></td>
    <td> 
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td>
    </tr>
    </table>
    </div>
    </form>
</body>
</html>

Code View:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=hightech;Initial Catalog=session; User ID=sa; password=sa");

        String str = "select ename,job from emp";
        SqlCommand cmd = new SqlCommand(str, con);
        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())
        {
            TextBox1.Text = dr["ename"].ToString();
            Label1.Text = dr["job"].ToString();
        }
        con.Close();
    }
}

Enjoy…