AlexC
AlexC

Reputation: 9661

C# variable, .NET

I have a problem in C#, Help me please in:

I have a dropdown list and some labels and

each ListItem VALUE from DDL is equal with each label ID

for example

                <asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true" >
                     <asp:ListItem Text="Route A - Toronto to Barrie" Value="RouteA">
                </asp:DropDownList>

               <asp:Label ID="RouteA" runat="server" Text="42"></asp:Label>

QUESTION:

 private Label ccc;

public void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.ccc.Text = DropDownList1.SelectedValue.ToString();
}

I my code is not what i Want.

I want to get selectet item value (DropDownList1.SelectedValue.ToString()) from DDL and put in some Variable (this.ccc) and after that I want to call label with the same ID .

Logical I want Something like this :

this.ccc = DropDownList1.SelectedValue.ToString(); (in My case this.ccc = "RouteA")

this.ccc.Text ="test" (in My case) (this.ccc.Text = "42");

Thank You very much, if You've understood, Please Help me !!

Upvotes: 0

Views: 222

Answers (4)

David Andres
David Andres

Reputation: 31781

I think you're looking for Page.FindControl.

Label label = (Label)Page.FindControl(DropDownList1.SelectedValue);
this.ccc.Text = label.Text;

I don't believe you need to call ToString() on the SelectedValue property because it is a string by definition.

There's a chance that your controls are deep within the page hierarchy, so you can use Jeff Atwood's recursive FindControl method (stolen from his one of his blog articles):

private Control FindControlRecursive(Control root, string id) 
{ 
  if (root.ID == id)
  { 
    return root; 
  } 

  foreach (Control c in root.Controls) 
  { 
    Control t = FindControlRecursive(c, id); 
    if (t != null) 
    { 
      return t; 
    } 
  } 

  return null; 
} 

Your code will change to:

Label label = (Label)FindControlRecursive(Page, DropDownList1.SelectedValue);
this.ccc.Text = label.Text;

Upvotes: 1

cdpnet
cdpnet

Reputation: 590

You need to try somewhat like this.

Control c = Page.FindControl(DropDownList1.SelectedValue); //You can choose to use other container than the Page instance itself

Label l = c as Label;

l.Text = "test";

Upvotes: 2

M4N
M4N

Reputation: 96551

I'm not sure I understand correctly, but:

// this returns the ID of the label
string labelId = DropDownList1.SelectedValue;

// now find the label with that ID
Label label = FindControl(labelId) as Label;

this.ccc.Text = label.Text;

Upvotes: 2

Canavar
Canavar

Reputation: 48088

How about this :

Label myLabel = (Label)Page.FindControl(DropDownList1.SelectedValue.ToString());
myLabel.Text = "test";

Upvotes: 2

Related Questions