2016-12-02 33 views
1

私はを持っていて、動的に作成しましたの中に動的に作成されたラジオボタンがあります。私はfindControl()ラジオボタンがあればそれを見つけることができますplaceholderの直属の子供。findControlを使用して子要素を見つけよう

私は文字通り昨日、彼らがPanelの子要素であるときにそれらを見つけることを試みました。どのようにこれを行う方法はありますか?ここで

は、以下の私のコードです:

PlaceHolder1.Controls.Add(myPanel); //add the panel to the placeholderenter code here 
myPanel.Controls.Add(myRadioButton); //add the radiobutton to the panel 
+1

[ 'にFindControl()']あなたは再帰を探している、求められています(http://stackoverflow.com/questions/4955769/better-way-to-find-control-in-asp-ネット) –

答えて

0

あなたは再帰的にそれはIDが使用してコントロールを検索する方法を確認する必要があります。つまり、このメソッドは、(あなたのケースでは)プレースホルダ内のコントロールを検索します。メソッドが制御を検出した場合は、それを返します。そうでない場合は、すべてのプレースホルダのサブコントロールを「深く」検索します。そして、何も見つからなかった場合、その後、それはすべてのプレースホルダサブコントロールサブコントロールなどでは、1つのより下のレベルに検索します)

private Control FindControl(string ctlToFindId, Control parentControl) 
{ 
    foreach (Control ctl in parentControl.Controls) 
    { 
     if (ctl.Id == ctlToFindId) 
      return ctl; 
    } 

    if (ctl.Controls != null) 
    { 
     var c = FindControl(ctlToFindId, ctl); 
     if (c != null) return c; 
    } 

    return null; 
} 

し、このようにそれを使用します。

再帰的コントロールを見つける
Control ctlToFind = FindControl(myRadioButton.Id, Placeholder1); 
if (ctlToFind != null) 
{ 
    //your radibutton is found, do your stuff here 
} 
else 
{ 
    // not found :(
} 
0

オプションもありますが、それにはdown-sidesもあります。あなたはすべてのコントロールのIDを知っている場合

あなただけFindControl

RadioButtonList myRadioButton = PlaceHolder1.FindControl("Panel1").FindControl("RadioButtonList1") as RadioButtonList; 
Label1.Text = myRadioButton.SelectedValue; 

を使用することができますしかし、あなたはあなたの動的に追加したコントロールIDを与える必要があります。

Panel myPanel = new Panel(); 
myPanel.ID = "Panel1"; 

RadioButtonList myRadioButton = new RadioButtonList(); 
myRadioButton.ID = "RadioButtonList1"; 

PlaceHolder1.Controls.Add(myPanel); 
myPanel.Controls.Add(myRadioButton); 
関連する問題