Author: Zunnair
Download Source Code : 885_FindControl.zip
In this simple article you will learn to find control in code behind and change its properties dynamically.
Create a web application in c#
Drag a button, five labels and one textbox on the form
Then write code on form load event
C#
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = "Initial text of lable1";
Label2.Text = "Initial text of lable2";
Label3.Text = "Initial text of lable3";
Label4.Text = "Initial text of lable4";
Label5.Text = "Initial text of lable5";
TextBox1.Text = "Label1";
}
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Label1.Text = "Initial text of lable1"
Label2.Text = "Initial text of lable2"
Label3.Text = "Initial text of lable3"
Label4.Text = "Initial text of lable4"
Label5.Text = "Initial text of lable5"
TextBox1.Text = "Label1"
End Sub
After that write some code on button click even
C#
protected void Button1_Click(object sender, EventArgs e)
{
Label lbl;
lbl = (System.Web.UI.WebControls.Label )FindControl(TextBox1.Text);
lbl.Text = "Text Changed to www.smspunch.com";
}
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lbl As Label
lbl = DirectCast(FindControl(TextBox1.Text), System.Web.UI.WebControls.Label)
lbl.Text = "Text Changed to www.smspunch.com"
End Sub
This is simple code to find control dynamically.