Click here to Skip to main content
15,614,814 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have few asp label controls within a form in aspx page. I am getting text values from database and now i want the label control's text to be assigned dynamically.

I am trying this:

C#
for(int i=1; i<5; i++)
 {
       Label mylabel = (Label)Page.FindControl("lblColName" + i);
      if (mylabel != null)
      {
        mylabel.Text = "Excellent!" + i;
      }
                       
 }


but getting null.

Please help me solving this.
Thank you in advance.

What I have tried:

even if i try below, i am getting null

C#
Label mylabel = (Label)Page.FindControl("lblColName");
      if (mylabel != null)
      {
        mylabel.Text = "Excellent!" ;
      }
Posted
Updated 8-May-21 9:02am
v2
Comments
Andy Lanng 29-Jul-19 6:13am    
It looks like your adding the controls dynamically. If so, can you show us the code you use to generate the labels, please.
Sneha Bhushan 29-Jul-19 6:35am    
i am not adding the labels dynamically, only i want to assign the label.text dynamically
Sneha Bhushan 29-Jul-19 6:37am    
<asp:label id="lblColName1" runat="server">
Sneha Bhushan 29-Jul-19 7:06am    
Hi, i tried it but dint work..

Hi body, i found your Quiestion in Stack Overflow.
c# - Using variable in label name [^]

I see this top link.
in your code you must put in object from label. like this below. and this solution is worked for me in Window Form Application. may be worked for you in aspx page.


C#
void Button1Click(object sender, EventArgs e)
{
    var test = 1;
    var labels = Controls.Find("label" + test, true);
    if (labels.Length > 0)
    {
        var label = (Label) labels[0];
        label.Text = "Some text goes here...";

    } 
}



and that's Done . you have access on it!!! Labels[0]
your code must be like this.


C#
for(int i=1; i<5; i++)
 {

       var labels = Page.FindControl("lblColName" + i);
      

      if (labels.Length > 0)
      {
        var mylabel = (Label) labels[0];
        mylabel.Text = "Excellent!" + i;
      }
                       
 }


i hope this worked for you. please tell me the result of this !! :)) tnx man
 
Share this answer
 
For example aspx page is like

<asp:button id="AddControlButton" runat="server" text="Click Me" onclick="AddControlButton_Click">
<asp:placeholder id="placeHolder" runat="server">


C#
protected void Page_Init(object sender, EventArgs e)
{
    var label = new Label();
    label.ID = "lblTest";
    label.Text = "Label Before Click";
    placeHolder.Controls.Add(label);
}


protected void AddControlButton_Click(object sender, EventArgs e)
{
    Label label = (Label)placeHolder.FindControl("lblTest");
    label.Text = "Label After Click!";
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900