C# Convert string to literal Control [closed]
I have a literal control named "ltlTextBox1" and "ltlTextBox2"
I would like to do something like this
for (int i = 1; i <= 2; i++)
{
string textbox = "ltlTextBox" + i;
textbox.Text = "Write this";
}
TextBox textbox = this.FindControl("ltlTextBox" + i) as TextBox;
if (textbox != null) {
textbox.Text = "Write this";
}
I believe there is a LiteralControl control in asp.net . This would most likely provide the functionality you need.
Other than that I think we might need more information to help you out as to what/how/where you are trying to use these literal controls.
(Expanding on this)
LiteralControl l = this.FindControl("ltlTextBox") as LiteralControl;
l.Text = "My Text";
in your code textbox is a variable of type string. String does not have a property called Text.
assigning a value to a variable doesn't change the name of the value. Ie ("ltlTextBox" + 1).ToString()
prints "ltlTextBox1" whereas ltlTextBox1.ToString()
prints System.Web.Ui.Controls.LiterlaControl or what ever the type of that variable is.
You either need to do:
ltlTextBox1.Text = "write this"; ltlTextBox2.Text = "Write this";
or
var controls = new[]{ ltlTextBox1, ltlTextBox2};
for(int i = 0;i<controls.Length;i++){
controls[0].Text = "Write this";
}
精彩评论