【问题标题】:asp.net dropdown list codes reuse across multiple pagesasp.net 下拉列表代码跨多个页面重用
【发布时间】:2012-10-03 16:28:59
【问题描述】:

我做过一些经典的 ASP,但对 ASP.NET 来说真的很陌生,所以如果可以的话,请给我一些步骤。

我尝试在不同页面的多个表单中重复使用相同的下拉列表代码。

我有 Form1.aspx 页面,它有这个:

<asp:DropDownList ID="Vendor" runat="server" 
AutoPostBack="True" 
onselectedindexchanged="ddlVendor_SelectedIndexChanged">
</asp:DropDownList>

然后文件Form1.aspx.cs页面后面的代码有这个来构建供应商下拉框的列表。

private void FillVendor()
{
    string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
    SqlConnection con = new SqlConnection(strConn);
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT VendorID, VendoName FROM Vendor";
    DataSet objDs = new DataSet();
    SqlDataAdapter dAdapter = new SqlDataAdapter();
    dAdapter.SelectCommand = cmd;
    con.Open();
    dAdapter.Fill(objDs);
    con.Close();
    if (objDs.Tables[0].Rows.Count > 0)
    {
        Vendor.DataSource = objDs.Tables[0];
        Vendor.DataTextField = "VendorName";
        Vendor.DataValueField = "VendorID";
        Vendor.DataBind();
        Vendor.Items.Insert(0, "--Select--");
    }
    else
    {
        lblMsg.Text = "No Vendor found";
    }


}

假设我有另一个 form2.aspx 页面和 form2.aspx.cs 页面。此页面将使用与 form1.aspx 页面相同的下拉列表。我不想在 form2.aspx 和 form2.aspx.cs 中再次重写相同的代码。有没有更好的方法来跨多个页面重复使用这些代码?

提前致谢,

【问题讨论】:

  • 将其开发为自定义控件并以这种方式重用?
  • 是 - 将可重用代码提取到 User Control

标签: asp.net


【解决方案1】:
  1. 您可以为自定义下拉列表创建用户控件
  2. 您可以编写接受 DropdownList 的方法,将标签作为参数,然后设置属性。

【讨论】:

    猜你喜欢
    • 2011-01-17
    • 2016-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2013-06-08
    相关资源
    最近更新 更多