Retrieve value of TextBox from another class
I have a C# class from which I would like to access a string contained within a TextBox
. The TextBox
is defined in a an .ascx
file. What headers should I put in the class to be able to access this开发者_如何学Go TextBox
string? A small example would be greatly appreciated, as I am new to ASP.NET. Thanks in advance.
Is this class supposed to be the "code-behind" for the .ascx file, or is it its own class?
If the former, how are you building it? Basically, the .ascx file needs to "inherit" from this class in its header and the class itself needs to extend UserControl
. There are samples and information here.
If the latter, the class shouldn't be able to access the page elements on the user control. What does the class do? Basically, any values that the class needs should be supplied to it, either as constructor arguments when building an instance of the class or as properties set on the class or as method arguments when calling the class' methods.
Can you share some code and describe the functionality you're looking to achieve?
Assuming MyUserControl.ascx inherits MyUserControl.cs, you can define a public property that exposes the value of your TextBox control. For example:
public class MyUserControl : System.Web.UI.UserControl {
public string MyTextBoxValue()
{
get
{
return MyTextBoxControl.Text;
}
}
}
Then all you have to do in your other class (which you're trying to access the TextBox's value from) is get a reference to the instance of your MyUserControl user control and you should be able to access your custom property:
string value = myUserControl.MyTextBoxValue();
精彩评论