qWolf
qWolf

Reputation: 43

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 !

Upvotes: 0

Views: 2367

Answers (3)

Pavel Chuchuva
Pavel Chuchuva

Reputation: 22455

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

Upvotes: 2

Andrew Hare
Andrew Hare

Reputation: 351466

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
}

Upvotes: 2

Traveling Tech Guy
Traveling Tech Guy

Reputation: 27811

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.

Upvotes: 0

Related Questions