Solved

Finding a user control - Three user controls loaded via code behind - Cannot find the textbox value of the search control.

Posted on 2004-10-17
11
225 Views
Last Modified: 2010-07-27
I have  a web page with a header, search and results controls.

The header control presents a logo at the top of the page, the search control presents a textbox and a button which when clicked will call call a results control which queries a SQL table and returns a populated datagrid.

The problem: I want to pass the string entered in the textbox of the search control to the results datagrid. I've used the following code in the search.ascx:

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSrch.Click, btnSearch.Click
        Dim ctlControl As Control

        ctlControl = LoadControl("results.ascx")

        plhResults.Controls.Add(ctlControl)

       
    End Sub
    Public ReadOnly Property srchTxt() As String

        Get
            Return TbSrch.Text
        End Get

    End Property
End Class


in the results.ascx:

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim srchTxt As String
        Dim _myControl As Control = Page.FindControl("UCtlsearch")
        Dim _myControlType As Type = _myControl.GetType()
        Dim _myUC_SrchTxt As PropertyInfo = _myControlType.GetProperty("srchTxt")
        srchTxt = _myUC_SrchTxt.GetValue(_myControl, Nothing)

        Dim ds As DataSet
        Dim conn As String
        Dim spName As String = "spGetPolicy"
        conn = ConfigurationSettings.AppSettings("DBQQStatus")
        Dim storedParams(1) As SqlParameter
        storedParams = SqlHelperParameterCache.GetSpParameterSet(conn, spName)
        storedParams(0).Value = srchTxt


        ds = SqlHelper.ExecuteDataset(conn, CommandType.StoredProcedure, spName, storedParams)

        DgPolicy.DataSource = ds
        'DgPolicy.DataMember = "Policies"
        DgPolicy.DataBind()
    End Sub

UCtlsearch is the id of the search control which is loaded from the header control.

The FindControl statement returns nothing.

Any ideas? I can supply the full code if required
0
Comment
Question by:BJM1M
  • 6
  • 4
11 Comments
 
LVL 20

Expert Comment

by:ihenry
Comment Utility

If the UCtlsearch is loaded and added to header's control collection you can't find it from the Page. Try to find in header instead, something like this:

UCtlHeader.FindControl( "UCtlsearch" )
0
 
LVL 18

Expert Comment

by:tusharashah
Comment Utility
Page.FindControl requires ID of the TextBox after the page has been render. & Since it is a UserControl ID would be slightly different then what you kept before:

If user control name is: UCtlsearch
& TextBox in UC is      : srchTxt
Run time ID of UC       : UCtlsearch1_srchTxt

------------------------------------------------------------------------------------------------------------
'replace this 4 line with line shown below:
Dim _myControl As Control = Page.FindControl("UCtlsearch")
        Dim _myControlType As Type = _myControl.GetType()
        Dim _myUC_SrchTxt As PropertyInfo = _myControlType.GetProperty("srchTxt")
        srchTxt = _myUC_SrchTxt.GetValue(_myControl, Nothing)

'----
Dim _myUC_SrchTxt As TextBox = Page.FindControl("UCtlsearch1_srchTxt")
srchTxt = _myUC_SrchTxt.Text
------------------------------------------------------------------------------------------------------------
if that dosn't help then.. do View Source & Find 'srchTxt' & check out how exactly the ID of srchTxt is changing


-tushar
0
 

Author Comment

by:BJM1M
Comment Utility
Neither of the above suggestions work. Even if I search for the ID of "CtlHeader__ctl0_TbSrch" which is what is shown in the source of the page when run.

Just to clarify,

The first page called "srchstat.aspx" loads the user control header with an UCtlHeader by using code behind. The HTML is:

<%@ Register TagPrefix="QuickQuote" TagName="Header" src="../controls/qqhead.ascx" %>
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="srchstat.aspx.vb" Inherits="qqsts.srchstat"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
      <HEAD>
            <title>WebForm1</title>
            <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
            <meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            <form id="Form1" method="post" runat="server">
                  <%-- Header of Main Page --%>
                  <QUICKQUOTE:HEADER id="UCtlHeader" Runat="Server"></QUICKQUOTE:HEADER>
            </form>
      </body>
</HTML>

The code behind for "srchstat.aspx" is

The HTML for qqhead.ascx is

<%@ Register TagPrefix="uc1" TagName="UCtlsearch" Src="search.ascx" %>
<%@ Control Language="vb" AutoEventWireup="false" Codebehind="qqhead.ascx.vb" Inherits="qqsts.qqhead" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<asp:image id="compLogo" runat="server"></asp:image><asp:placeholder id="plhSearch" Runat="server"></asp:placeholder>

The code behine for qqhead.ascx

Public Class qqhead
    Inherits System.Web.UI.UserControl

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents compLogo As System.Web.UI.WebControls.Image
    Protected WithEvents plhSearch As System.Web.UI.WebControls.PlaceHolder

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'Put user code to initialize the page here
        Dim ctlControl As Control
        'Check if o.k to proceed based on security check
        If security.check(Request.QueryString("ID")) = False Then
            Response.Write(security.ErrMsgType("DENIED"))
            compLogo.Visible = False
            Exit Sub
        End If
        compLogo.ImageUrl = "../img/" + MdbQuery.FLookup("DBData", "LogoFileName", "Security", "SecurityString = '" & Request.QueryString("ID") & "'")
        ctlControl = LoadControl("search.ascx")

        plhSearch.Controls.Add(ctlControl)
    End Sub

End Class

Notice I am using a PLACEHOLDER

The results.ascx is as per the code in the original post.

Does the use of the Placeholder plhSearch affect the use of the FindControl?



0
 
LVL 20

Expert Comment

by:ihenry
Comment Utility
Try to give ID to the search.ascx

        ctlControl = LoadControl("search.ascx")
        ctlControl.ID = "UCtlsearch"
        plhSearch.Controls.Add(ctlControl)

Then search from the header

        UCtlsearch ctl = CType( Page.UCtlHeader.FindControl( "UCtlsearch" ), UCtlsearch )
        Dim srchTxt As String = ctl.srchTxt

0
 

Author Comment

by:BJM1M
Comment Utility
Placing the code:

 UCtlsearch ctl = CType( Page.UCtlHeader.FindControl( "UCtlsearch" ), UCtlsearch )
        Dim srchTxt As String = ctl.srchTxt

in the vb code behind of  results.aspx does not work as it doesn't know anything about UCtlsearch and UCtlHeader as they are not declared.

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 20

Expert Comment

by:ihenry
Comment Utility

Declare UCtlHeader in srchstat.aspx, like this

       Protected WithEvents UCtlHeader As System.Web.UI.UserControl

the same as ID in this line

       <QUICKQUOTE:HEADER id="UCtlHeader" Runat="Server"></QUICKQUOTE:HEADER>

And within result.ascx

       ' I assumed class name in code behind search.ascx is UCtlsearch
        UCtlsearch ctl = CType( Page.UCtlHeader.FindControl( "UCtlsearch" ), UCtlsearch )
        Dim srchTxt As String = ctl.srchTxt

Set ID property when loading search.ascx in qqhead.ascx

        ctlControl = LoadControl("search.ascx")
        ctlControl.ID = "UCtlsearch"
        plhSearch.Controls.Add(ctlControl)
0
 

Author Comment

by:BJM1M
Comment Utility
UCtlsearch and UCtlHeader are not defined in result.ascx do you want these to be defined? If not the code beloe will not work

UCtlsearch ctl = CType( Page.UCtlHeader.FindControl( "UCtlsearch" ), UCtlsearch )
        Dim srchTxt As String = ctl.srchTxt

Giving the control an ID in qqhead.ascx is fine...


0
 
LVL 20

Expert Comment

by:ihenry
Comment Utility

Sorry, I missed out something that make it doesn't work

declare UCtlHeader in srchstat.aspx, the variable name must be the same with the id used in aspx

       Public WithEvents UCtlHeader As System.Web.UI.UserControl

Then in result.ascx

       ' I assumed class name in code behind search.ascx is UCtlsearch
        UCtlsearch ctl = CType( Page, srchstat ).UCtlHeader.FindControl( "UCtlsearch" )
        Dim srchTxt As String = ctl.srchTxt

I don't know class name defined in code behind search.ascx so I assumed it is UCtlsearch. That should work, I have tested it.
0
 
LVL 20

Accepted Solution

by:
ihenry earned 500 total points
Comment Utility
oo..my bad..I mixed up c# with vb.net

replace UCtlsearch with the actual class name that contains the readonly property srchTxt.
Dim ctl As ActualClassName = CType( Page, srchstat ).UCtlHeader.FindControl( "UCtlsearch" )
0
 

Author Comment

by:BJM1M
Comment Utility
YES!

YES!

Thanks - IT WORKS!

Is there anywhere that you can point me to , so that I can read up on this area of control manipulation?

Regards & thanks again

Brian
0
 
LVL 20

Expert Comment

by:ihenry
Comment Utility

Well, Brian..no problem. glad your problem solved. I gotta go for a few hours and come back with some articles that might be useful for you.

Cheers!
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
I recently went through the process of creating a Calendar Control of events with the basis of using a database to keep track of the dates that are selectable, one requirement was to have the selected date pop-up in a simple lightbox.  At first this…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now