使用用户控件的ASP.NET C#下拉列表

10

首先,我是ASP.NET的新手。

为了在不同页面和表单中重用我的下拉列表,我被建议使用用户控件来实现。所以我阅读了一些关于用户控件方面的内容,并尝试去操作它,但由于我对ASP.NET还很陌生,所以无法使其工作。出现了以下错误:

Cannot access a non-static member of outer type 'ASP.Vendor' via nested type 'ASP.Vendor._Default'

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>

很显然,我是新手,肯定做错了什么。请问有人可以帮助我或者给我一个用户控件下拉列表的例子,并告诉我如何将其包含在表单中吗?谢谢!

3个回答

2
我看到的第一个问题是您在UserControl内部继承了Page:
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

使用Codebehind文件

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

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

示例项目结构
enter image description here

标记(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" />

Codebehind

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";
            }
        }
    }
}

另一种方法 - 移除类声明

如果由于某些原因您不想添加codebehind文件,可以完全删除类声明并将代码直接包含在其中。

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

    // etc
</script>

作为一则旁注,我建议将数据访问逻辑放到一个独立的类中,以便更好地分离和重用,但是在你纠正了上述问题后,你所概述的结构应该能够工作。

1
这并不完全正确 - 通过将类定义放置在 <script runat=server> 标签中,_Default 也成为运行时编译的 ASCX 类中的嵌套类。 - x0n
如果没有添加代码后台,应该完全删除类声明。 - Tim M.
它可以工作了!感谢Tim提供的详细信息,这真的帮助我让它运行起来了。 - Milacay
@Milacay 你说的“Form Details”是什么意思?你在哪里找到的? - Dean
它无法正常工作,而且在“添加评论”中很难解释,因此我发布了一个新问题,以包含更多有关问题的详细信息。如果您有机会,请查看[link]https://dev59.com/OGnWa4cB1Zd3GeqPyDVv[/link] 谢谢! - Milacay
显示剩余2条评论

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

0
你正在使用Visual Studio吗?如果是的话,你应该使用提供的模板,因为这样会更容易,而且你完全可以避免这个问题。例如,要添加一个用户控件,你可以右键单击你想要放置它的文件夹(在解决方案资源管理器中),然后选择添加 -> 新项目。然后选择Web用户控件,给它一个名称,然后点击添加。

感谢大家的帮助,特别是@Tim。我终于让它工作了。非常感激! - Milacay
我已经成功显示了下拉列表,但现在我不知道下拉列表的ID是什么。 - Milacay
你能具体说明一下吗?你是想在C#代码中使用ID还是在javascript中使用? - Dean
@Milacay,我刚看到你对Tim的评论:.Net在传递给客户端之前会更改ID,以避免冲突。因此,在您的C#代码中使用的ID是“ddlVendorList”,但如果您想要访问浏览器中的下拉列表,则会有所不同(例如“VendorList_ddlVendorList”)。 - Dean

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接