Home > database >  using string as control id in C# ASP.NET
using string as control id in C# ASP.NET

Time:02-01

i have a page with 2 textbox items and a button textbox1 contains a word , and textbox2 is empty

now i want to put content of TextBox1.Text in TextBox2.Text with button click,

i tried:

protected void Button1_Click(object sender, EventArgs e) 
{ Page.FindControl("TextBox2").Text = TextBox1.Text; }

this code don't work ,how to make this work?

CodePudding user response:

You are trying to access the Text property of the TextBox2 control, but you are using the FindControl method to find the control. The FindControl method returns a Control object, and the Text property is not available on the Control class. To access the Text property, you need to cast the result of the FindControl method to a TextBox:

protected void Button1_Click(object sender, EventArgs e) 
{ 
    TextBox textBox2 = (TextBox)Page.FindControl("TextBox2");
    textBox2.Text = TextBox1.Text; 
}
  • Related