Convert a string to value of control
I have a string str = "txtName.Text" (txtName is name of textbox control)
How to display value of textbox without is value of 开发者_如何学运维string str (use C#)
Let me a solution.
Thanks a lot !
Probably the easiest thing to do would be to extract the control id like this:
String controlId = str.Substring(0, str.IndexOf('.'));
Then use the Page.FindControl
method to find the control and cast that as an ITextControl
so that you can get the Text
property value:
ITextControl textControl
= this.FindControl(controlId) as ITextControl;
if (textControl != null)
{
// you found a control that has a Text property
}
I assume that the question is: How to get value of textbox control given its ID as a string.
Use FindControl method.
Example:
TextBox myTextBox = FindControl("txtName") as TextBox;
if (myTextBox != null)
{
Response.Write("Value of the text box is: " + myTextBox.Text);
}
else
{
Response.Write("Control not found");
}
If by "value" you mean "numeric value", then you can't - text boxes contain strings only. What you can do is get the string like you did, and parse that string into a number.
You can use int.Parse()
or double.Parse()
(depending on the type), or TryParse()
for a safer implementation.
精彩评论