Previous .text element in dropdown list

I am using MS VS 2010 and working on the ASP.NET C # website. I was stuck on something that, in my opinion, might be pretty simple, maybe not.

Suppose 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 programmatically created our drop-down list, we also need to create our custom event handler, to which we are attached.

 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 } 

That is where my problem is. Read the comments in the event handler. (Sorry if my syntax is disabled, at the moment it's all free)

I have the feeling that I can get the previous selected index (or an element that doesn't matter) from the event arguments ((DropDownList) e).?

Please help>. <This does not seem too bad!

+4
source share
1 answer

I don't think there is a built-in mechanism, but you can use ViewState or HiddenField to save the previous index. 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; } 
+4
source

Source: https://habr.com/ru/post/1381331/


All Articles