Pergunta

I have a for each loop in the final step of my asp:Wizard that is supposed to list all of the text in each textbox that is not null. The textboxes are in the second step of the asp:Wizard and they are placed in asp:Panel controls that are made visible or not visible with the use of checkboxes on the same step. Here is the event with the loop:

protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {
        var requested = this.Controls.OfType<TextBox>()
                         .Where(txt => !string.IsNullOrWhiteSpace(txt.Text));

        var sb = new StringBuilder();
        foreach (var textBox in requested)
        {
            sb.Append(textBox.Text); //Add the text not the textbox
            sb.Append("</br>"); //Add a line break to make it look pretty
        }
        Label1.Text = sb.ToString();

    }

If I run the application with the loop my label will return blank, no matter what I fill out. The label is currently in the 3rd step

<asp:WizardStep ID="WizardStep3" runat="server" AllowReturn="false" Title="Step 3" StepType="Complete">
        <asp:Label ID="Label1" runat="server" Text="This text will display when I run the application without the foreach loop"></asp:Label>
</asp:WizardStep>
Foi útil?

Solução

and they are placed in asp:Panel

With this.Controls You are looking for the TextBoxes which exist directly on the form not inside the panel.

You should modify your query to get controls from the panel like:

var requested = yourPanel.Controls.OfType<TextBox>()
                         .Where(txt => !string.IsNullOrWhiteSpace(txt.Text));

where yourPanel is the id of your asp:Panel

Outras dicas

You want to find a control recursively if it is nested inside other controls. Here is the helper method.

public static Control FindControlRecursive(Control root, string id)
{
   if (root.ID == id) 
      return root;

   return root.Controls.Cast<Control>()
      .Select(c => FindControlRecursive(c, id))
      .FirstOrDefault(c => c != null);
}

Usage

var testbox = FindControlRecursive(Page, "NameOfTextBox");
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top