Author: Zunnair
Download Source Code : 897_HREF_in_Code_behind.zip
In this simple article you will learn to access div control in code behind using server side tag.
Create a web application in c#.
Drag a button, one div (HTML) and one textbox on the form. Now when you try to access div on code behind, you can’t do this. Because it is client side control, so first put server tag in this and assign it a id.
<div id="Div1" runat="server">
This text is in the Client side dive you can change this text by pressing button aboove.
div>
Then write code on form load event
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
Button1.Text = "change text of div";
TextBox1.Text = "Div control article...";
}
catch (Exception ex)
{
Div1.InnerText = ex.Message;
}
}
}
VB
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
Try
Button1.Text = "change text of div"
TextBox1.Text = "Div control article..."
Catch ex As Exception
Div1.InnerText = ex.Message
End Try
End If
End Sub
After that write some code on button click even
C#
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (TextBox1.Text != "")
{
Div1.InnerText = TextBox1.Text;
}
else
{
Div1.InnerText = "No Text in TextBox";
}
}
catch (Exception ex)
{
Div1.InnerText=ex.Message;
}
}
VB
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Try
If TextBox1.Text <> "" Then
Div1.InnerText = TextBox1.Text
Else
Div1.InnerText = "No Text in TextBox"
End If
Catch ex As Exception
Div1.InnerText = ex.Message
End Try
End Sub
This is simple code to access Div control in code behind.