asp.net的DropDownList同步 [英] asp.net DropDownList in sync

查看:76
本文介绍了asp.net的DropDownList同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有选择的用户控件内一年三下拉菜单。负载我指定一个下拉选择的值。另外两个下拉菜单会自动得到分配相同选择的值。不管我分配哪些下拉列表中选择的价值,他们三个会得到相同选择的值。我试着重新为下拉式菜单中一个新的用户控制,但同样的事情发生。

I have three dropdowns for selecting a year inside a user control. On load I specify the selected value for one drop down. The other two drop downs are automatically getting assigned the same selected value. No matter which dropdown I assign a selected value to, they all three get the same selected value. I've tried recreating a new user control for the dropdowns but the same thing happens.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="DropDownTest.ascx.cs" Inherits="WymanOrgManagement.DropDownTest" %>
<p>
    <asp:DropDownList ID="ddlStartDateYear" runat="server">
    </asp:DropDownList>
</p>
<p>
    <asp:DropDownList ID="ddlEndDateYear" runat="server">
    </asp:DropDownList>
</p>
<p>
    <asp:DropDownList ID="Year" runat="server"></asp:DropDownList>
</p>

code背后:

Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WymanOrgManagement
{
    public partial class DropDownTest : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            populateDatesAndStates();
            ddlEndDateYear.SelectedIndex = 2;
        }

        protected void populateDatesAndStates()
        {
            ListItem init2 = new ListItem();
            init2.Text = init2.Value = "Year...";
            ddlStartDateYear.Items.Add(init2);
            ddlEndDateYear.Items.Add(init2);
            Year.Items.Add(init2);

            for (int i = DateTime.Now.Year - 1; i < DateTime.Now.Year + 10; i++)
            {
                ListItem item = new ListItem();
                item.Text = item.Value = i.ToString();
                ddlStartDateYear.Items.Add(item); ddlEndDateYear.Items.Add(item);
                Year.Items.Add(item);
            }
        }
    }
}

有人可以帮助我弄清楚为什么三个下拉菜单似乎是同步?谢谢!

Can someone help me figure out why the three dropdowns seem to be in sync? Thanks!

推荐答案

这三个下拉列表分享列表项同样的实例。当你将其设置为在一个地方,它在所有3个地方被选中。

All three dropdowns share the same instances of ListItem. When you set it to be Selected in one place, it becomes selected in all 3 places.

ListItem item = new ListItem();
item.Text = item.Value = i.ToString();
ddlStartDateYear.Items.Add(item); 
ddlEndDateYear.Items.Add(item);
Year.Items.Add(item);

什么你可能想要做的就是这个。

What you probably want to do is this

ddlStartDateYear.Items.Add( i.ToString() ); 
ddlEndDateYear.Items.Add( i.ToString() );
Year.Items.Add( i.ToString() );

这将创建列表项的新实例(具有相同的值)进入每个列表。

This will create a new instance of ListItem (with the same values) to go into each list.

这篇关于asp.net的DropDownList同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆