【问题标题】:how to access controls from class files in app code如何从应用程序代码中的类文件访问控件
【发布时间】:2012-01-11 17:38:49
【问题描述】:

如何从应用代码中的类文件中访问控件?

标记:

<%@ Page Language="vb" AutoEventWireup="false" Inherits="shoppingCart1.ShoppingPage" CodeFile="ShoppingPage.aspx.vb" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
    <HEAD>
        <title>ShoppingPage</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>
        <form id="Form1" method="post" runat="server" name="Form1">
            <TABLE id="tblShopping" style="FONT-SIZE:10pt;FONT-FAMILY:verdana" borderColor="black"
                width="100%" cellSpacing="0" cellPadding="0" border="1" runat="server">
                <tr style="FONT-SIZE:10pt;FONT-FAMILY:verdana;color:white;background-color:#336699;font-weight:bold;">
                    <td colspan="4">PRODUCT LIST</td>
                </tr>
                <tr>
                    ***<td id="cellshoping" runat="server" colspan="4" width="100%"></td>***
                </tr>
                <tr>
                </tr>
            </TABLE>
        </form>
    </body>
</HTML>

App_Code 文件夹中的 ShoppingCart.vb

Imports Microsoft.VisualBasic
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Public Class ShoppingCart
    Public Sub bindData()
        Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
        Dim objDA As SqlDataAdapter
        Dim myRow As SqlDataReader
        Dim comd As New SqlCommand("SELECT * FROM products", con)
        con.Open()
        myRow = comd.ExecuteReader()
        Dim strRowGen As String = ""
        While myRow.Read()
            strRowGen = strRowGen & "<TR>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
            strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
            strRowGen = strRowGen & "</TR>"
            **cellshoping**.InnerHtml = strRowGen
        End While
    End Sub
End Class

我在cellshoping.InnerHtml 收到错误“cellshoping is not declared”...如何从应用代码中的类文件访问用户控件??

在后面添加了 ASPX 代码

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration


Namespace shoppingCart1

Partial Class ShoppingPage
    Inherits System.Web.UI.Page
#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 Label1 As System.Web.UI.WebControls.Label
Protected WithEvents Label2 As System.Web.UI.WebControls.Label
Protected WithEvents Label3 As System.Web.UI.WebControls.Label
Protected WithEvents txtNK As System.Web.UI.WebControls.TextBox
Protected WithEvents txtCF As System.Web.UI.WebControls.TextBox
Protected WithEvents txtHA As System.Web.UI.WebControls.TextBox
Protected WithEvents dtGrdProducts As System.Web.UI.WebControls.DataGrid


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
    'Load data by calling function bindData()
            Dim sCart = New ShoppingCart
            If Not Page.IsPostBack Then

                cellshoping.InnerHtml = sCart.bindData()
            End If
    Dim strQty As Integer
    Dim proId As String
    Dim delId As String

    delId = Request.QueryString("delItemId")
    proId = Request.QueryString("itemId")
        '------ Following portion act as controller where code is written as
        '------ per the action from the request of the pages like Add To Cart,
        '------ Update Cart & Delete Cart
    strQty = 1
    If Request.QueryString("Actn") <> "" Then
        If Request.QueryString("Actn").Equals("Add") Then
                    If Request.QueryString("itemId") <> "" Then
                        AddToSession(proId, strQty)
                        Response.Redirect("./ShoppingCart.aspx")
                    End If
        ElseIf Request.QueryString("Actn").Equals("Del") Then
            If Request.QueryString("delItemId") <> "" Then
                Session.Remove(delId)
                Response.Redirect("./ShoppingCart.aspx")
            End If
        ElseIf Request.QueryString("Actn").Equals("Update") Then
            If Request.QueryString("itemUpId") <> "" And Request.QueryString("quantity") <> "" Then
                If IsNumeric(Request.QueryString("itemUpId")) Then
                    updateCart(Request.QueryString("itemUpId"), Request.QueryString("quantity"))
                    Response.Redirect("./ShoppingCart.aspx")
                Else
                    Response.Redirect("./ShoppingCart.aspx")
                End If
            End If
        End If
    End If
End Sub
Private Sub AddToSession(ByVal strProduct As String, ByVal intQty As Integer)
    If Not Session(strProduct) Is Nothing Then
        Session.Add(strProduct, CInt(Session(strProduct)) + intQty)
    Else
        Session.Add(strProduct, intQty)
    End If
End Sub
Private Sub updateCart(ByVal strProduct As String, ByVal qty As Integer)
    If Not Session(strProduct) Is Nothing Then
        Session.Add(strProduct, CInt(qty))
    End If
End Sub

End Class
End Namespace

【问题讨论】:

    标签: asp.net .net vb.net


    【解决方案1】:

    假设 ShoppingCart 类在页面的代码隐藏中某处被引用并且 BindData() 方法是从该代码中调用的,那么您有几个选择:

    1) 将页面引用传递给购物车的绑定数据方法。

    2) 将BindData()方法中的数据返回给页​​面,这样页面就可以适当地更新页面中的数据了。

    3) 您可以访问 HttpContext.Current.Handler 并将其转换为您的页面实例。

    我的建议是,特别是如果您想在其他页面中使用该类,我的建议是创建一个接口,该接口具有可用于更新数据并使用选项 1 或 3 的方法,或者实现选项 2。

    这是一个示例,说明如何更改代码以实现和接口。

    界面:

    Public Interface IShoppingCartPage
        Sub UpdateData(sCartContents As String)
    End Interface
    

    页面代码隐藏(部分):

    Public Class ShoppingPage
        Implements IShoppingCartPage
    
        Public Sub UpdateData(sCartContents As String) Implements IShoppingCartPage.UpdateData
            cellshopping.innerHtml = sCartContents
        End Sub
    End Class
    

    最后是修改后的购物车类(注意使用了stringbuilder类,会比问题中的字符串concat效率高很多):

    Public Class ShoppingCart
        Public Sub bindData(oPage As IShoppingCartPage)
            Using con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
                Using comd As New SqlCommand("SELECT * FROM products", con)
                    con.Open()
                    Using oReader As SqlDataReader = comd.ExecuteReader()
                        Dim sbHTML As New System.Text.StringBuilder(5000)
                        While oReader.Read()
                            sbHTML.Append("<TR>")
                            sbHTML.Append("<TD>").Append(oReader.GetValue(0)).Append("</TD>")
                            sbHTML.Append("<TD>").Append(oReader.GetValue(1)).Append("</TD>")
                            sbHTML.Append("<TD>").Append(oReader.GetValue(2)).Append("</TD>")
                            sbHTML.Append("<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=").Append(oReader.GetValue(0)).Append("';document.Form1.submit();"">Add To Cart</TD>")
                            sbHTML.Append("</TR>")
                        End While
    
                        oPage.UpdateData(sbHTML.ToString())
                    End Using
                End Using
                con.Close()
            End Using
        End Sub
    End Class
    

    【讨论】:

    • competent_tech 你可能想让你对他的回复更友好。跨度>
    • 请详细说明......正如@DJKRAZE 所说......我不明白该怎么做。
    • 你好...请解释一下..给我一些教程,或者如果你有空,请帮助我。
    • 我已经用特定代码更新了答案,以显示必要的更改。我还修改了答案以解决数据库连接处于打开状态且资源未正确处理的问题。
    【解决方案2】:

    为什么不让你的方法返回一个字符串?

    Public Function bindData() as String
        Dim con As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
        Dim objDA As SqlDataAdapter
        Dim myRow As SqlDataReader
        Dim comd As New SqlCommand("SELECT * FROM products", con)
        con.Open()
        myRow = comd.ExecuteReader()
        Dim strRowGen As String = ""
        While myRow.Read()
            strRowGen = strRowGen & "<TR>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(0) & "</TD>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(1) & "</TD>"
            strRowGen = strRowGen & "<TD>" & myRow.GetValue(2) & "</TD>"
            strRowGen = strRowGen & "<TD><a href='#' onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
            strRowGen = strRowGen & "</TR>"            
        End While
        Return strRowGen
    
    End Sub
    

    然后你可以从你的页面调用它

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
       'Set innerHtml here
       'cellshoping.InnerHtml = ShoppingCart.bindData()
    End Sub
    

    【讨论】:

    • 好的..我正在使用您的技术..当我尝试运行页面时显示"'bindData' is not a member of 'shoppingCart1.ShoppingCart'. "
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多