将DropDownLists添加到用户控件C#

时间:2016-06-21 14:20:14

标签: c# .net controls

我从未在C#.NET中使用过用户控件,我正在开发一个项目,我有3个下拉列表,需要将它们放入用户控件中。我想知道如何做到这一点。我将发布我的下拉列表的代码,以及屏幕抓取它们当前的样子,以及它们应该是什么样子。感谢。

 public partial class _default2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DropDownList1.DataBind();
                DropDownList1_SelectedIndexChanged(sender, e);
                DropDownList2.DataBind();
                DropDownList2_SelectedIndexChanged(sender, e);
                DropDownList3.DataBind();
            }
        }

        // Drop Down List 1
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            XmlDataSource2.XPath = String.Format("mmsdata/mill[@n='{0}']/mach", DropDownList1.SelectedValue);
        }
        // Drop Down List 2
        protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
        {
            XmlDataSource3.XPath = String.Format("mmsdata/mill[@n='{0}']/mach[@n='{1}']/srn", DropDownList1.SelectedValue, DropDownList2.SelectedValue);
            BindSensorList();
        }

        protected void BindSensorList()
        {
            //sender.GetType();
            XmlDocument xdoc = XmlDataSource3.GetXmlDocument();
            XmlNodeList nodes = xdoc.SelectNodes(XmlDataSource3.XPath);
            var sensors = new List<Sensor>();
            foreach (XmlNode node in nodes)
            {
                sensors.Add(new Sensor { id = node.Attributes["n"].Value, name = node.InnerText });
            }

            DropDownList3.DataSource = sensors;
            DropDownList3.DataValueField = "id";
            DropDownList3.DataTextField = "name";
            DropDownList3.DataBind();
        }

我希望它们看起来像什么

First picture

他们的样子

Second Picture

1 个答案:

答案 0 :(得分:1)

将下拉列表添加到用户控件的最简单方法是在项目解决方案中创建用户控件,然后将asp.net webform代码放在ui中,然后您可以为它编写代码,就像您一样创建一个Web表单。

示例用户控制

<%@ Control Language="C#" ClassName="SampleUserControl" %>
<h3> <u>User Control</u> </h3>
<script runat=server>
</script>
Drop down 1:    <asp:DropDownList id="ColorList"
                AutoPostBack="True"
                OnSelectedIndexChanged="Selection_Change"
                runat="server">

              <asp:ListItem Selected="True" Value="White"> White </asp:ListItem>
              <asp:ListItem Value="Silver"> Silver </asp:ListItem>
              <asp:ListItem Value="DarkGray"> Dark Gray </asp:ListItem>
              <asp:ListItem Value="Khaki"> Khaki </asp:ListItem>
              <asp:ListItem Value="DarkKhaki"> Dark Khaki </asp:ListItem>
           </asp:DropDownList>
<asp:label id="Label1" runat=server/>

您可以在页面上使用用户控件并动态加载其内容,只需在您希望使用它的页面上初始化它,并以与加载类/页面相同的方式传入值

相关问题