简体   繁体   中英

Button cannot access text box

My .aspx:

<asp:LoginView runat="server">
    <RoleGroups>
        <asp:RoleGroup Roles="admin">
            <ContentTemplate>
                <asp:TextBox ID="TextBox" runat="server"></asp:TextBox>
                <asp:Button ID="Button" runat="server" Text="Submit" OnClick="Button_Click" />
            </ContentTemplate>
        </asp:RoleGroup>
    </RoleGroups>
</asp:LoginView>

My code-behind

public partial class WebForm3 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Button_Click(object sender, EventArgs e)
    {

        string Mystring = String.Format("{0}", /*I want to put Textbox.text here*/ );

    }
}

The problem is that I get a "Textbox" is not defined in the current context. I fiddled around a bit and found that removing the loginview restores the functionality that I want. So why does the loginview break my ability to reference across controls that are in the same view?

C# is case sensitive. Instead of the name Textbox (b is in lower case) use TextBox. Also, I recommend you change the ID of your controls to something more meaningful. Do not set the ID of a TextBox to "TextBox"

Further to your comments, you seem to have your TextBox inside a LoginView. The only way I could get access to this control is

Control container = new Control();
LoginView1.RoleGroups[0].ContentTemplate.InstantiateIn(container);
foreach (Control control in container.Controls)
{
    if (control.ID == "txtName")
    {
        //Phew. Got your control
    }
}

Note: I have set the LoginView ID to LoginView1 and TextBox ID to txtName

Try this.TextBox ! that should solve the Case Sensitivity thing! also... bad variable naming... As a rule of thumb, do not name a variable exactly like the name of a class...

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