简体   繁体   中英

Implementing logic from aspx.cs to aspx page

I am trying to make all TextBox controls read only in my .aspx page. I've written this in my aspx.cs page:

private void SetTextBoxReadOnly(Control parent, bool readOnly)
{
  // Get all TextBoxes and set the value of the ReadOnly property.
  foreach (var tb in parent.Controls.OfType<TextBox>())
    tb.ReadOnly = readOnly;

  // Recurse through all Controls
  foreach(Control c in parent.Controls)
    SetReadOnly(c, readOnly);
}

Obviously I have a ton of TextBoxes in the .aspx page such as this one:

                <div class="form-group">
                    <asp:Label runat="server" AssociatedControlID="txtTimePointsExplained" CssClass="col-md-2 control-label">Explain why these time points:</asp:Label>
                    <div class="col-md-10">
                        <asp:TextBox ID="txtTimePointsExplained" TextMode="MultiLine" Rows="8" runat="server" CssClass="form-control"></asp:TextBox></div>
                </div>

Obviously it's not making my textboxes readOnly. I don't think there is anything wrong with the logic, which leads me to believe it's not being interpreted by the .aspx page.

There was an error within the original code snippet:

private void SetTextBoxReadOnly(Control parent, bool readOnly)
{
  // Get all TextBoxes and set the value of the ReadOnly property.
  foreach (var tb in parent.Controls.OfType<TextBox>())
    tb.ReadOnly = readOnly;

  // Recurse through all Controls
  foreach(Control c in parent.Controls)
    SetReadOnly(c, readOnly);
}

Here:

SetReadOnly(c, readOnly); 

should be the original method:

SetTextBoxReadOnly(c, readOnly); 

As David said in the comments to invoke this method on the page (at the time it loads) Call this method in the Page_Load method:

protected void Page_Load(object sender, EventArgs e)
    {
        SetTextBoxReadOnly(this, true);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM