我在内容页面中使用了Find控件来查找内容页面本身的文本框。但是它返回null。我已经尝试了很多方法,但即使下面没有工作也是我的代码......
private void showw()
{
try
{
Page page = HttpContext.Current.Handler as Page;
ContentPlaceHolder mainContent = (ContentPlaceHolder)page.FindControl("ContentPlaceHolder1");
// ContentPlaceHolder mainContent = (ContentPlaceHolder)page.Page.Master.FindControl(");
TextBox TxtPId = (TextBox)mainContent.FindControl("ContentPlaceHolder1_TxtPId");
TextBox TxtPId1 = (TextBox)this.Master.FindControl("Content2").FindControl("TxtPLName ");
if (TxtPId!=null)
{
insertString = @"select [Patientid] as 'Patient id' ,[LastName] as'Last Name',[FirstName],[MiddleName],[AliasName] , [PHN],[PhoneNo], CONVERT(varchar,DateOfBirth,105) as 'Date Of Birth' from PatientMaster where Patientid like '" + TxtPId+ "%'";
TxtPId1.Text = "Last name";
}
GridView GridView1 = (GridView)page.FindControl("ContentPlaceHolder1_GridView1");
GridView1.DataSource = null;
SqlCommand cmd = new SqlCommand(insertString, connect);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "PatientMaster");
GridView1.DataSource = ds;
if (ds.Tables[0].Rows.Count == 0)
Label1.Visible = true;
else
Label1.Visible = false;
GridView1.DataBind();
ModalPopupExtender1.Show();
}
catch { }
}
注意:
我必须在内容页面中为该页面文本框使用查找控件,而不是母版页。
答案 0 :(得分:0)
1。在我们使用FindControl
获取对MainContent
的引用之前,我们首先需要对母版页控件的引用。获得对母版页的引用后,我们可以通过MainContent ContentPlaceHolder
引用FindControl
,并从那里引用TextBox
(再次使用FindControl
)。
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//can be called on page load
show();
}
protected void btnShow_Click(object sender, EventArgs e)
{
//can be called on any event
show();
}
private void show()
{
MasterPage ctl00 = FindControl("ctl00") as MasterPage;
// Get a reference to the ContentPlaceHolder
ContentPlaceHolder MainContent = ctl00.FindControl("ContentPlaceHolder1") as ContentPlaceHolder;
// Reference the Label and TextBox controls
TextBox myControl1 = MainContent.FindControl("txtTest") as TextBox; //your textbox Id here *ex:* txtPId
if (myControl1 != null)
{
//Control myControl2 = myControl1.Parent;
//Response.Write("Parent of the text box is : " + myControl2.ID);
Response.Write("Text is: " + myControl1.Text);
}
else
{
Response.Write("Control not found");
}
}
}
需要提及 2。 ctl00
,因为母版页及其ContentPlaceHolders都充当命名容器。
它有效!
有用的文章:Control ID Naming Issues