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

01<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
02 
03<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 
06<head runat="server">
07    <title></title>
08</head>
09<body>
10    <form id="form1" runat="server">
11    <div>
12    <table>
13    <tr>
14    <td>
15        <asp:Label ID="Label1" runat="server" Text=""></asp:Label></td>
16    <td>
17        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> </td>
18    </tr>
19    </table>
20    </div>
21    </form>
22</body>
23</html>

Code View:-

01using System;
02using System.Collections.Generic;
03using System.Linq;
04using System.Web;
05using System.Web.UI;
06using System.Web.UI.WebControls;
07using System.Data;
08using System.Data.SqlClient;
09 
10public partial class _Default : System.Web.UI.Page
11{
12    protected void Page_Load(object sender, EventArgs e)
13    {
14        SqlConnection con = new SqlConnection("Data Source=hightech;Initial Catalog=session; User ID=sa; password=sa");
15 
16        String str = "select ename,job from emp";
17        SqlCommand cmd = new SqlCommand(str, con);
18        con.Open();
19        SqlDataReader dr = cmd.ExecuteReader();
20        if (dr.Read())
21        {
22            TextBox1.Text = dr["ename"].ToString();
23            Label1.Text = dr["job"].ToString();
24        }
25        con.Close();
26    }
27}

Enjoy…