user3657245
user3657245

Reputation: 1

How to populate multiple labels with only one text box?

I am trying to populate one label after another using only one textbox. Right now it always populates label3, but not label4, what is wrong with the logic?

protected void Button5_Click(object sender, EventArgs e)
{
    if (Label3.Text == null)
    {
        Label3.Text = TextBox1.Text;
    }
    else 
    {
        Label4.Text = TextBox1.Text;
    }
}

Upvotes: 0

Views: 308

Answers (3)

Kevin
Kevin

Reputation: 2631

You could loop through all the labels on the form (you could also do this recursivley) and do something like this. You could also put in more checks if you only want to update certain labels.

foreach (Control ctl in this.Controls)
{
    if (ctl.GetType() == typeof(Label))
    {
        Label l = (Lablel)ctl;
        if (String.IsNullOrEmpty(l.Text)) l.Text = TextBox1.Text;
    }
}

Upvotes: 1

Willz
Willz

Reputation: 78

You must be looking for something like this:

protected void Button5_Click(object sender, EventArgs e)
{
    if (StringIsNullOrEmpty(Label3.Text))
    {
        Label3.Text = TextBox1.Text;
    }

    if (StringIsNullOrEmpty(Label4.Text))
    {
        Label4.Text = TextBox1.Text;
    }
}

In your sample you have the Label4 assingment under the else statement, wich will only be executed case the if statement returns false (Label3.Text != null).

Upvotes: 0

Nathan A
Nathan A

Reputation: 11319

Basic logic here. See your problem in the comments.

if (Label3.Text == null)
{
    Label3.Text = TextBox1.Text;
}
else 'this will NEVER HAPPEN IF Label3.Text is NULL
{

    Label4.Text = TextBox1.Text;
}

Instead, do this

if (Label3.Text == null)
{
    Label3.Text = TextBox1.Text;
}

if (Label4.Text == null)
{
    Label4.Text = TextBox1.Text;
}

Upvotes: 0

Related Questions