How to Find Textbox Id in UserControl and show to you Pge
If you resgister the user control in the .aspx page,then you can access the TextBox values directly in code behind.
Firstly create User Control ...
.ascx page
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="attachfile.ascx.cs" Inherits="attachfile" %>
<asp:TextBox ID="TextBox1" runat="server" meta:resourcekey="TextBox1Resource1"></asp:TextBox>
then .ascx.cs Page
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class attachfile : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public string Text
{
get { return TextBox1.Text; }
set { TextBox1.Text = value; }
}
}
then come out our .aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register src="attachfile.ascx" tagname="attachfile" 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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:attachfile ID="attachfile1" runat="server" />
</div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</form>
</body>
</html>
and last come our .aspx.cs Page
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
//first way....
//attachfile uc = (attachfile)LoadControl("~/attachfile.ascx");
//uc.Text =
//form1.Controls.Add(uc);
//attachfile use = LoadControl(~/attachfile.ascx);
second way...
TextBox box = (TextBox)this.attachfile1.FindControl("TextBox1");
string str = box.Text;
Response.Write("<script> alert('"+str+"')</script>");
Response.Write(str);
}
}
end ....................
If you want to access the textbox property in codebehind as intellisence property, simply make it a string property in the user control.
- In the user control, create a public string property that returns textbox string value..
public string MyText { get { return txt1.Text; } }
- Register the user control on the page
<%@ Register TagPrefix="uc" TagName="MyControl" Src="~/mycontrol.ascx" />
and declare it..<uc:MyControl ID="control1" runat="server" />
- From the codebehind now you can read the property..
Response.Write(control1.MyText);
Hope it helps
Thanks.
No comments:
Post a Comment