[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

ASP.NET: referencing objects inside a ContentPlaceHolder control

Posted on 2007-10-17
15
Medium Priority
?
1,627 Views
Last Modified: 2008-01-09
I'm developing a site in ASP.NET using vbscript. I have set up a master page with a ContentPlaceHolder control. Each time the master page is used, I'd like to display a counter value. Do I place the label that will display the counter value inside or outside of the content control and how do I reference it from the code behind coding area?

Thanks!
0
Comment
Question by:wppiexperts
  • 7
  • 6
  • 2
15 Comments
 
LVL 4

Expert Comment

by:davehunt00
ID: 20096659
Place the counter on the master page.

You can reference by casting to a local control and accessing that control. For example, if the counter total is displayed in a label (lbCounter on the master page):

In the content page:
dim myLabel as Label  'as a global
then in page_load (or wherever):
myLabel = CType(Master.FindControl("lbCounter"), Label)
then do what you want with myLabel

hth
davehunt00
0
 

Author Comment

by:wppiexperts
ID: 20096977
When you indicated to declare the myLabel in the content page, is that the code behind page?

Right now I have it declared on the code behind page under the Partial Class section. When I run the page it throws out a NullReferenceException error (troubleshooting tipes include use the "new" keyword, check if the the object is null, etc.). I have set up the object with default text, so shouldn't that prevent a NULL issue?
0
 
LVL 4

Expert Comment

by:davehunt00
ID: 20097025
Yes, that's right.  All the code I gave should be in the content page code-behind. The only thing in the master page is the lbCounter label control itself.  The dim line can be right under your class heading (probably under "Inherits System.Web.UI.Page"), but before the page_load sub.  You should be running the content page, not the master page.  Just to be sure, check the page declaration in the content page source and make sure you see MasterPageFile="~/yourMasterPageName".

You have the label (with some dummy text) on the master page with ID = lbCounter, correct?  And it is in the "master" part of the page, not in the ContentPlaceHolder region?

If that doesn't clarify, maybe post your code.
Dave


0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 26

Expert Comment

by:Rejojohny
ID: 20098503
>>Each time the master page is used, I'd like to display a counter value

just adding the label in the master page will not help .. you will also need to persist it .. if you need to count the number of time it is displayed for every user, then use the application object to store the value .. if you need to count how many times the master page is used, then use a session varaible .. i will try and show the code using the session

in master's page load
Dim myctr as int32
if session("Count") is nothing then
  myctr = 1
else
   myctr = session("count") + 1
end if
response.write ("Count : " + myctr)
session("Count") = myctr
0
 

Author Comment

by:wppiexperts
ID: 20101246
I should clarify that the "counter" is actually a hyperlink to a shopping cart page, the text displayed for the hyperlink is the current count of items in the cart as it relates to the user. Each time the master page is used (it contains the header info - menu structure) I want the quantity updated via the page_load event.
0
 

Author Comment

by:wppiexperts
ID: 20101641
OK, here is the code from the master page:
<%@ Master Language="VB" CodeFile="x_master.master.vb" Inherits="x_master"  %>
<!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>
    <link href="~/App_Themes/xTheme/xStyles.css" type="text/css" rel ="stylesheet" />    
</head>
<body>

    <form id="form1" runat="server">
   
    <!-- Header -->
    <div class="Header">
    <asp:Image ID="Image1" runat="server"
    ImageUrl="~/Images/x.xg" Width="760" Height="130"
    alternateText="Text" />
    </div>
   
      <!--// The head of the menus //-->

      <oem:Menu id="MenuMain"  runat="server" ShowEvent="Always" StyleFolder="Images"
            Position="Horizontal" CSSMenu="ParentMenu" CSSMenuItemContainer="ParentItemContainer" Width="530">
            <CSSClassesCollection>
            </CSSClassesCollection>
            <Components>
            </Components>
      </oem:Menu>

      <!--// The menus //-->


      <oem:Menu id="Menu3" runat="server" ShowEvent="MouseOver" AttachTo="MyAccount" Align="Under" OffsetVertical="-4" OffsetHorizontal="-1" Width="240" StyleFolder="Images">
      </oem:Menu>
            <asp:HyperLink ID="cartCount" runat="server" NavigateUrl="~/x_cart.aspx" Visible="False" Width="120px">0 Items in Cart</asp:HyperLink><div>
        <asp:contentplaceholder id="ContentPlaceHolder1" runat="server">
            </asp:contentplaceholder>
    </div>
    </form>
</body>
</html>

and the code from the master code behind page:
Imports System.Data.SqlClient
Imports System.Data

Partial Class x_master
    Inherits System.Web.UI.MasterPage
    Dim myLink As HyperLink

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim cartConnection As New sqlconnection("Server=xSQL;Database=xSQL;Trusted_Connection=yes")
        Dim cartSQL As New SqlCommand("SELECT count(*) from cart where user_userid = " & Session("userid"))
        myLink = CType(Master.FindControl("cartCount"), HyperLink)
        If Session("username") = "" Then
            myLink.Visible = False

        Else
            myLink.Visible = True
            cartSQL.Connection.Open()
            Dim returnObject As Object = cartSQL.ExecuteScalar()
            If Not returnObject Is Nothing Then
                Dim cartContent As Integer = CInt(returnObject)
                cartConnection.Close()
                If cartContent = 0 Then
                    cartCount.Text = "0 Items in Cart"
                Else
                    cartCount.Text = cartContent & " Items in Cart"
                End If
            End If
        End If
    End Sub
End Class


it's still failing on the line:
myLink = CType(Master.FindControl("cartCount"), HyperLink

any suggestions?
Thanks!
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20103238
try
 myLink = CType(Page.FindControl("cartCount"), HyperLink)
or
 myLink = CType(Me.FindControl("cartCount"), HyperLink)

instead of
 myLink = CType(Master.FindControl("cartCount"), HyperLink)
0
 

Author Comment

by:wppiexperts
ID: 20103371
what is the purpose of the CType function if the variable myLink and cartCount are both of type HyperLink already?
0
 

Author Comment

by:wppiexperts
ID: 20103570
One other question I have is what is the purpose of declaring objects as "New" throughout the code. For example, I'm now getting the error to use the "new" keyword to create an object instance of "cartSQL.Connection.Open() when it was declared within the same subroutine just a few lines above:

        Dim cartConnection As New sqlconnection("Server=xSQL;Database=xSQL;Trusted_Connection=yes")
        Dim cartSQL As New SqlCommand("SELECT count(*) from cart where user_userid = " & Session("userid"))
        myLink = CType(Me.FindControl("cartCount"), HyperLink)
        If Session("userid") = Nothing Then
            myLink.Visible = False
        Else
            myLink.Visible = True
==>      cartSQL.Connection.Open()

what does it need to be "redeclared" and how do I do that?
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20103778
findcontrol does not know what type of control is been found .. you need to tell it to convert it into hyperlink object ..

>>what does it need to be "redeclared" and how do I do that?
cartSQL.Connection.Open()
must be
cartConnection.Open()

Rejo
0
 

Author Comment

by:wppiexperts
ID: 20104740
huh....OK, this throws my limited understanding of all of this for a bit of loop, sorry if I keep tacking on questions here...
so if I use cartConnection.Open().....how/where do I execute the sql statement that pulls in the data? In this case I'm going to run ExecuteScalar to return a count value.
0
 
LVL 26

Accepted Solution

by:
Rejojohny earned 1200 total points
ID: 20108598
open the connection and attach it to the command object .. the rest of the code will work ... and do remove the code I have mentioned above

        Dim cartConnection As New SqlConnection("Server=xSQL;Database=xSQL;Trusted_Connection=yes")
        cartConnection.Open()
        Dim cartSQL As New SqlCommand("SELECT count(*) from cart where user_userid = " & Session("userid"), cartConnection)
myLink = CType(Master.FindControl("cartCount"), HyperLink)
        If Session("username") = "" Then
            myLink.Visible = False
        Else
            myLink.Visible = True
            Dim returnObject As Object = cartSQL.ExecuteScalar()
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20108607
i think even this must work
        Dim cartSQL As New SqlCommand("SELECT count(*) from cart where user_userid = " & Session("userid"), New SqlConnection("Server=xSQL;Database=xSQL;Trusted_Connection=yes"))
.. and no need for the connection object ...
0
 

Author Comment

by:wppiexperts
ID: 20108817
I'm increasing the point value due the amount of work you have put into this. Thank you very much, the routine is working great!
0
 
LVL 26

Expert Comment

by:Rejojohny
ID: 20108853
thanks and glad that you got that working ..

Rejo
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this Article, I will provide a few tips in problem and solution manner. Opening an ASPX page in Visual studio 2003 is very slow. To make it fast, please do follow below steps:   Open the Solution/Project. Right click the ASPX file to b…
One of the pain points with developing AJAX, JavaScript, JQuery, and other client-side behaviors is that JavaScript doesn’t allow for cross domain request for pulling content. For example, JavaScript code on www.johnchapman.name could not pull conte…
Loops Section Overview
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses
Course of the Month17 days, 21 hours left to enroll

830 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