简体   繁体   English

下拉列表的上一个item.text

[英]Previous item.text of the Drop Down List

I am using MS VS 2010, and working on an ASP.NET C# website. 我正在使用MS VS 2010,并在ASP.NET C#网站上工作。 I am stuck on something that I think may be quite simple, maybe not though. 我坚持认为可能很简单的事情,也许不是。

Lets say I have a drop down list. 可以说我有一个下拉列表。

DropDownList ddl = new DropDownList();
ddl.ID = "d355";
dynamicPanel.Controls.Add(ddl);

ListItem lstItem1 = new ListItem();
lstItem1.Text = "1";
ListItem lstItem2 = new ListItem();
lstItem2.Text = "2";

ddl.Items.Add(lstItem1);
ddl.Items.Add(lstItem2);
ddl.SelectedIndexChanged += new EventHandler(this.ddl_SelectedIndexChanged);

Since we programatically created our drop down list, we need to also create our custom event handler that we tied to it. 由于我们以编程方式创建了下拉列表,因此我们还需要创建与之绑定的自定义事件处理程序。

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
    // add the selected index to a counter
    counter +=((DropDownList)sender).SelectedIndex;
    // Now this is where I get stuck, if the current selected index is less
    // than the previous selected index, I want to subtract from the counter



}

This is where my problem lies. 这就是我的问题所在。 Please read the comments in the event handler. 请阅读事件处理程序中的注释。 (Sorry if I have some of the syntax off, this is all free hand at the moment) (对不起,如果我关闭了一些语法,这一切都是免费的)

I have a feeling that I can get the previous selected index (or item it doesn't matter) from the event args ((DropDownList)e).? 我有一种感觉,我可以从事件args((DropDownList)e)获得先前选择的索引(或无关紧要的项)。

Please help >.< This doesn't seem too bad! 请帮助>。<这似乎不太糟糕!

I don't think that there is a built in mechanism, but you could use ViewState or a HiddenField to keep the previous index. 我不认为有内置机制,但您可以使用ViewStateHiddenField来保留以前的索引。 Something like the following: 类似于以下内容:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
    {
        int selectedIndex = ((DropDownList)sender).SelectedIndex;
        if (selectedIndex < (int)ViewState["PreviousIndex"])
        {
            counter -= ((DropDownList)sender).SelectedIndex;
        }
        else
        {
            counter += ((DropDownList)sender).SelectedIndex;
        }
        // update the index
        ViewState["PreviousIndex"] = selectedIndex;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM