Bind (Populate) Label using SqlDataSource from Code Behind in ASP.Net

Last Reply 24 days ago By pandeyism

Posted 24 days ago

I want to bind sqldata source with label control so how can i do it?

please help me.

Posted 24 days ago

Hi nid@patel,

Refer below code.

HTML

<asp:Label ID="lblName" runat="server" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
    ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" DataSourceMode="DataSet"
    SelectCommand="SELECT [Name] FROM [Customers] WHERE ([Id] = ?)" OnSelecting="SqlDataSource1_Selecting">
    <SelectParameters>
        <asp:Parameter Name="Id" Type="Int32" />
    </SelectParameters>
</asp:SqlDataSource>

Namespaces

C#

using System.Data;

VB.Net

Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        foreach (DataRowView row in dv)
        {
            lblName.Text = row["Name"].ToString();
        }
    }
}

protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
    e.Command.Parameters["Id"].Value = 1;
}

VB.Net

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)Handele Me.Load
        If Not Me.IsPostBack Then
            Dim dv As DataView = CType(SqlDataSource1.[Select](DataSourceSelectArguments.Empty), DataView)
            For Each row As DataRowView In dv
                lblName.Text = row("Name").ToString()
            Next
        End If
    End Sub

    Protected Sub SqlDataSource1_Selecting(ByVal sender As Object, ByVal e As SqlDataSourceSelectingEventArgs)
        e.Command.Parameters("Id").Value = 1
    End Sub