实现从aspx.cs到aspx页面

时间:2015-10-18 20:32:23

标签: c# asp.net

我试图让所有TextBox控件只在我的.aspx页面中读取。我在aspx.cs页面中写了这个:

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);
}

显然我在.aspx页面中有很多TextBoxes,比如这个:

                <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>

显然,这并不是我的文本框只读。我不认为逻辑有什么问题,这让我相信它不会被.aspx页面解释。

1 个答案:

答案 0 :(得分:0)

原始代码段中存在错误:

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);
}

下面:

SetReadOnly(c, readOnly); 

应该是原始方法:

SetTextBoxReadOnly(c, readOnly); 

正如大卫在评论中所说,在页面上调用此方法(在加载时)在Page_Load方法中调用此方法:

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