【问题标题】:ASP.NET C# Dropdown List using User Control使用用户控件的 ASP.NET C# 下拉列表
【发布时间】:2012-10-03 23:57:47
【问题描述】:

首先,我是 ASP.NET 新手

为了在不同页面上的不同表单中重复使用我的下拉列表,建议我使用用户控件来完成此操作。 因此,我阅读了一些有关用户控制的内容并尝试使用它,但由于我是 ASP.NET 的新手,所以无法让它工作。得到这个错误:

无法通过嵌套类型“ASP.Vendor._Default”访问外部类型“ASP.Vendor”的非静态成员

1) 我创建了一个 Controls\Vendor.ascx 文件

<% @ Control Language="C#" ClassName="Vendor" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.UI" %>
<%@ Import Namespace="System.Web.UI.WebControls" %>
<%@ Import Namespace="System.Configuration" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Collections.Generic" %>

<script runat="server">

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillVendor();
        }
    }


    private void FillVendor()
    {
        string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
       System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SELECT VendorID, VendorName FROM Vendor";
        DataSet objDs = new DataSet();
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;;
        conn.Open();
        dAdapter.Fill(objDs);
        conn.Close();

        if (objDs.Tables[0].Rows.Count > 0)
        {
            VendorList.DataSource = objDs.Tables[0];
            VendorList.DataTextField = "VendorName";
            VendorList.DataValueField = "VendorID";
            VendorList.DataBind();
            VendorList.Items.Insert(0,"-- Select --");
        } else {
             lblMsg.Text = "No Vendor Found";
        }
    }
}
</script>
<asp:DropDownList ID="VendorList" runat="server" AutoPostBack="True" >
</asp:DropDownList>

2) 我使用此代码创建了一个 Tes2.aspx 页面,以查看是否可以拉出该供应商下拉列表,但没有运气。

<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc" TagName="Vendor" 
    Src="Controls\Vendor.ascx" %>
<html>
<body>
Testing
<form runat="server">
    <uc:Vendor id="VendorList" 
        runat="server" 
        />
</form>
</body>

显然,我是新手,一定做错事。有人可以帮助我或给我一个用户控件中的下拉列表示例以及如何将其包含在表单中吗?谢谢!

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    我看到的第一个问题是你从Page 内部的UserControl 继承:

    public partial class _Default : System.Web.UI.Page
    

    改为从UserControl 继承。

    // notice that I also renamed the class to match the control name
    public partial class Vendor : System.Web.UI.UserControl
    

    使用代码隐藏文件

    正如@x0n 所指出的,您的用户控件代码可以放在代码隐藏文件中(当您在 Visual Studio 中创建用户控件时自动创建)。用户控件通常由标记部分 (.ascx)、代码隐藏 (.ascx.cs) 和设计器文件 (.ascx.designer.cs) 组成。 HTML 标记进入 ASCX 文件,绑定代码进入代码隐藏。

    我建议保存您的代码,删除您当前的用户控件,然后通过 Visual Studio 重新添加它。

    示例项目结构

    标记 (ASCX) 文件

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VendorListControl.ascx.cs" Inherits="MyNamespace.VendorListControl" %>
    <asp:DropDownList runat="server" ID="ddlVendorList" />
    <asp:Label runat="server" ID="lblMessage" />
    

    代码隐藏

    using System;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace MyNamespace
    {
        public partial class VendorListControl : System.Web.UI.UserControl
        {
            protected void Page_Load( object sender, EventArgs e ) {
                if( !IsPostBack ) {
                    FillVendors();
                }
            }
    
            private void FillVendors() {
                string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection( strConn );
    
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "SELECT VendorID, VendorName FROM Vendor";
    
                DataSet objDs = new DataSet();
                SqlDataAdapter dAdapter = new SqlDataAdapter();
                dAdapter.SelectCommand = cmd; ;
                conn.Open();
                dAdapter.Fill( objDs );
                conn.Close();
    
                if( objDs.Tables[0].Rows.Count > 0 ) {
                    this.ddlVendorList.DataSource = objDs.Tables[0];
                    this.ddlVendorList.DataTextField = "VendorName";
                    this.ddlVendorList.DataValueField = "VendorID";
                    this.ddlVendorList.DataBind();
                    this.ddlVendorList.Items.Insert( 0, "-- Select --" );
                }
                else {
                    this.lblMessage.Text = "No Vendor Found";
                }
            }
        }
    }
    

    替代方法 - 删除类声明

    如果您出于某种原因不想添加代码隐藏文件,请完全删除类声明并在其中包含代码。

    <script runat="server">
        protected void Page_Load(object sender, EventArgs e){
            if (!IsPostBack){
                FillVendor();
            }
        }
    
        // etc
    </script>
    

    附带说明一下,我会将数据访问逻辑放在一个单独的类中以进行适当的分离/重用,但是一旦您纠正了上述问题,您概述的结构应该可以工作。

    【讨论】:

    • 不完全是这样 - 通过将类定义放在
    • true,除非添加代码隐藏,否则应完全删除类声明。
    • 有效!感谢蒂姆提供的详细信息,这确实帮助我让它工作。
    • 我让它显示下拉列表,但现在我不知道下拉列表的 ID 是什么。当我查看“表单详细信息”时,我看到了这个“
    • @Milacay “表单详细信息”是什么意思 - 你在哪里找到的?
    【解决方案2】:

    不要将类的定义放在 ASCX 本身中。创建一个单独的 CS 文件并使用 &lt;%@ Control ... 指令上的 CodeBehind 属性引用单独的文件。 ASP.NET 运行时将在首次访问时编译您的 ASCX 和 CS。

    【讨论】:

      【解决方案3】:

      您使用的是 Visual Studio 吗?如果是这样,您应该使用提供的模板,因为它可以更容易,并且您可以一起避免这个问题。例如,要添加用户控件,您可以右键单击要放入的文件夹(位于解决方案资源管理器中),然后转到添加 -> 新项目。然后选择 Web User Control,为其命名并单击添加。

      【讨论】:

      • 感谢大家的帮助,尤其是@Tim。我终于让它工作了。赞赏!
      • 我可以显示下拉列表,但现在我不知道下拉列表的 ID 是什么。
      • 你能说得更具体点吗?您是尝试在 C# 代码中还是通过 javascript 使用 ID?
      • @Milacay 我刚刚看到您对 Tim 的评论:.Net 在 ID 到达客户端之前更改了 ID,以免发生冲突。因此,您在 C# 代码中使用的 ID 是“ddlVendorList”,但如果您尝试访问浏览器中的下拉列表,它会有所不同(如“VendorList_ddlVendorList”)
      猜你喜欢
      • 2020-03-17
      • 2016-05-06
      • 1970-01-01
      • 2022-07-24
      • 1970-01-01
      • 2016-08-03
      • 2020-02-16
      • 2010-09-12
      相关资源
      最近更新 更多