Setting and getting Textbox value inside user control (ascx
control) from aspx page is a usual practice in both simple and complex
projects.
In this tutorial, we will
- Create New User Control.
- Add User Control in aspx Page.
- Set Textbox Value inside User Control
- Get Textbox value From User Control
Create New User Control
- Right Click on Project, Click Add New Item.
- A pop up window
will be opened.
- Select Web User Control from list, change its Name to 'myControl' and click Add.
- Two files will be added with name 'myControl.ascx' and 'myControl.ascx.cs'
Replace the code in 'myControl.ascx' file with following code.
<%@ Control
Language="C#"
AutoEventWireup="true"
CodeFile="myControll.ascx.cs"
Inherits="Controls_myControll"
%>
<table>
<tr>
<td>
Name :
</td>
<td>
<asp:TextBox ID="txtName"
runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Age :
</td>
<td>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Profession :
</td>
<td>
<asp:TextBox ID="txtProfession"
runat="server"></asp:TextBox>
</td>
</tr>
</table>
Add following code in 'myControl.ascx.cs' File.
public string Name
{
get { return
txtName.Text.ToString(); }
set { txtName.Text = value;
}
}
public string Age
{
get { return
txtAge.Text.ToString(); }
set { txtAge.Text = value;
}
}
public string
Profession
{
get { return
txtProfession.Text.ToString(); }
set { txtProfession.Text = value;
}
}
Add User Control in aspx Page
- Create New aspx Page with name ‘PageForWebControl’.
- Open Design View and drag and drop user control on it. Some code will be added in 'PageForWebControl.aspx' page automatically.
Page will look
like this.
<%@ Page
Language="C#"
AutoEventWireup="true"
CodeFile="PageForWebControl.aspx.cs"
Inherits="PageForWebControl"
%>
<%@ Register
src="Controls/myControll.ascx"
tagname="myControll"
tagprefix="uc1"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:myControll ID="myControll1"
runat="server"
/>
</div>
</form>
</body>
</html>
Set Textbox Value inside User Control
Add following code snippet in Page Load Event of 'PageForWebControl.aspx' page to set Values of Textbox inside
User Control.
// Setting Values in ASCX Control
myControll1.Name = "Waqas Ali";
myControll1.Age = "24";
myControll1.Profession = "Computer
Scientist";
Get Textbox value From User Control
Add following code snippet in Page Load Event of PageForWebControl.aspx
page to get values of Textbox from User Control.
string _name = string.Empty;
int _age = 0;
string _profession = string.Empty;
// Getting Values from ASCX Control
_name
= myControll1.Name;
_age
= Convert.ToInt32(myControll1.Age);
_profession = myControll1.Profession;
Now you are all done. Run Project and test your values.