[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

05/05/2009 at 12:40PM PDT, ID: 24382611
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

9.3

DropdownList items are cleared on postback

Asked by smacca in Programming for ASP.NET, Microsoft Visual C#.Net, C# Programming Language

Tags: dropdownlist postback

Hi,

I have created a custom dropdownlist that gets its values from a datasource (database).
My problem exists, when the page is posted back to itself - the items in the list are not persisted.

In my code, I can see why this happens - it is because I am not refilling the list automatically on postback (common practice).
However, how does the list refill itself.


     Q: Are the items in the list, supposed to be maintained across postback (must I call some methods like CreateChildControls)????
     Q: Do I have to rebind the list in the lists SelectedIndexChanged event handler (like you would with a GridView/DataList etc)????


This has been an issue for sometime now - to resolve it, I have just removed the !Page.IsPostBack condition (however, as this suggests, the code gets run when leaving pages etc which is inefficient - this is the main reason for it being there).

Hopefully, this is a 101 question - and I have missed this lesson early in my career.

Any help appreciated - thanks for your time.

Cheers.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
using System;
using System.Web.UI.WebControls;
using System.Collections;
using System.ComponentModel;
 
namespace MWeb.Web.UI.WebControls
{
	/// <summary>
	/// Base Class for Extra Item <code>DropDownList</code>s
	/// </summary>
	abstract public class ExtraItemDropDownList : System.Web.UI.WebControls.DropDownList, IExtraItemList
    {
        #region Declarations
 
        #region Constants
 
        public const string DEFAULT_EXTRAITEM_TEXT = "None";
		public const string DEFAULT_EXTRAITEM_VALUE = "0";
 
		public const string DEFAULT_DATATEXT_FIELD = "DataTextField";
		public const string DEFAULT_DATAVALUE_FIELD = "DataValueField";
 
        public const int DEFAULT_CACHE_TIME_IN_MINS = 0;
 
		#endregion
 
        #region Member Variables
 
        //private bool _hasDataBind = false;
 
        #endregion
 
        #endregion
 
        #region Constructor
 
        public ExtraItemDropDownList():
                base()
		{
            this.Init += new EventHandler(this.Control_Init);
            this.Load += new EventHandler(this.Control_Load);
            this.PreRender += new EventHandler(this.Control_PreRender);
        }   
 
		#endregion
 
		#region Abstract and Virtuals
 
		protected abstract void Fill();
		public virtual void Refresh()
		{
            //clear all items.
            this.Items.Clear();
 
            //refill.
            this.Fill();
 
            //clean data.
            this.IsDirtyData = false;
		}
 
		#endregion
 
		#region Control Events
 
		///<summary>
		///Fills the DropDownList with items from the database on the first request
		///If PopulateOnLoad is true. Will populate itself on any request where
		///IsDirtyData is true.
        ///</summary>       
        private void Control_Init(object sender, System.EventArgs e)
        {
            if ((!Page.IsPostBack && this.PopulateOnLoad) || this.IsDirtyData)
            {
                this.Refresh(); ////////////////*************THIS IS NOT EXECUTED ON POSTBACK (AS EXPECTED) - BUT IT FILLS THE LIST!!!! QUESTION: Are the list items suppossed to be maintained across postback or am I supposed to rebind the list!
            }
        }
 
        private void Control_Load(object sender, System.EventArgs e)
        {
 
        }
 
        private void Control_PreRender(object sender, System.EventArgs e)
        {
            //disable if only single item.
            if (this.DisableSingleItem && this.Enabled)
            {//must already be enabled!
 
                this.Enabled = this.IncludeExtraItem ? (this.Items.Count > 2) : (this.Items.Count > 1);
            }
 
            //remove excluded values.
            if (!string.IsNullOrEmpty(this.ExcludedValueList))
            {
                string[] excludedValues = this.ExcludedValueList.Split(new char[] { ',', ' ' });
                foreach (string excludedValue in excludedValues)
                {
                    this.Items.Remove(this.Items.FindByValue(excludedValue));
                }
            }
        }
 
        public override void DataBind()
        {
            //bind data.
            //try
            //{
                //base.DataBind();
            //}
            //catch { ;} //TODO: THIS IS A HACK - a selected index exception was being thrown when I was filtering/refreshing lists. Couldnt find a solution so this was a temp fix.
 
            //create new list item
            if (this.IncludeExtraItem)
            {
                ListItem newItem = new ListItem();
                newItem.Text = this.ExtraItemText;
                newItem.Value = this.ExtraItemValue;
                newItem.Selected = false;
 
                //add list item to specified position
                if ((this.ExtraItemPosition == ExtraItemPosition.Top || this.ExtraItemPosition == ExtraItemPosition.Start))
                {
                    this.Items.Insert(0, newItem);
                }
                else if ((ExtraItemPosition == ExtraItemPosition.Bottom || this.ExtraItemPosition == ExtraItemPosition.End))
                {
                    this.Items.Add(newItem);
                }
            }
 
            // now select the default item
            if (this.InitialValue.ToString().Length > 0)
            {
                for (int i = 0; i < this.Items.Count;i++)
                {
                    ListItem li = this.Items[i];
                    if (li.Value == this.InitialValue)
                    {
                        if (!li.Selected)
                            li.Selected = true;
                        break;
                    }
                }
            }
 
            //set binded flag.
            //this._hasDataBind = true;
        }		
		
		#endregion
 
		#region Properties
 
        [Description("Sets the cache time in minutes for the list."), Category("Loading")]
        public int CacheTimeInMins
        {
            get
            {
                if (this.ViewState["CacheTimeInMins"] == null)
                {
                    this.ViewState["CacheTimeInMins"] = DEFAULT_CACHE_TIME_IN_MINS;
                }
                return (int)this.ViewState["CacheTimeInMins"];
            }
            set
            {
                this.ViewState["CacheTimeInMins"] = value;
            }
        }
 
        [Description("If you set this value to true before the Load event occurs then the control will reload its self."), Category("Loading")]
        public bool IsDirtyData
        {
            get
            {
                if (this.ViewState["IsDirtyData"] == null)
                {
                    this.ViewState["IsDirtyData"] = false;
                }
                return (bool)this.ViewState["IsDirtyData"];
            }
            set
            {
                this.ViewState["IsDirtyData"] = value;
            }
        }
 
        [Description("If you set this value to true then this control will pre-populate itself when it loads."), Category("Loading")]
        public bool PopulateOnLoad
        {
            get
            {
                if (this.ViewState["PopulateOnLoad"] == null)
                {
                    this.ViewState["PopulateOnLoad"] = true;
                }
                return (bool)this.ViewState["PopulateOnLoad"];
            }
            set
            {
                this.ViewState["PopulateOnLoad"] = value;
            }
        }
 
        [Description("The value of the initially selected item"), Category("Data")]
        public string InitialValue
        {
            get
            {
                if (this.ViewState["InitialValue"] == null)
                {
                    this.ViewState["InitialValue"] = string.Empty;
                }
                return (string)this.ViewState["InitialValue"];
            }
 
            set
            {
                this.ViewState["InitialValue"] = value;
            }
        }
 
		[Description("bool:  Include extra item in list?"),Category("Extra")]
		public bool IncludeExtraItem
		{
			get
			{
				if(this.ViewState["IncludeExtraItem"]==null)
				{
					this.ViewState["IncludeExtraItem"] = false;
				}
				return (bool) this.ViewState["IncludeExtraItem"];
			}
			set
			{
				this.ViewState["IncludeExtraItem"] = value;
			}
		}
 
		[Description("bool:  Should the extra item always been shown at the top of the list"),Category("Extra")]
		public ExtraItemPosition ExtraItemPosition
		{
			get
			{
				if(this.ViewState["ExtraItemPosition"]==null)
				{
					this.ViewState["ExtraItemPosition"] = ExtraItemPosition.Top;
				}
				return (ExtraItemPosition) this.ViewState["ExtraItemPosition"];
			}
			set
			{
				this.ViewState["ExtraItemPosition"] = value;
			}
		}
 
		[Description("string:  The text string displayed for extra item"),Category("Extra")]
		public string ExtraItemText
		{
			get
			{
				if(this.ViewState["ExtraItemText"]==null)
				{
					this.ViewState["ExtraItemText"] = string.Empty;
				}
				return (string) this.ViewState["ExtraItemText"];
			}
			set
			{
				this.ViewState["ExtraItemText"] = value;
			}
		}		
 
		[Description("string:  The value used for the extra item"),Category("Extra")]
		public string ExtraItemValue
		{
			get
			{
                if (this.ViewState["ExtraItemValue"] == null)
				{
                    this.ViewState["ExtraItemValue"] = string.Empty;
				}
                return (string)this.ViewState["ExtraItemValue"];
			}
			set
			{
                this.ViewState["ExtraItemValue"] = value;
			}
        }
 
        [Description("If you set this to true, the list will disabled when their is only one item in the list."), Category("Loading")]
        public bool DisableSingleItem
        {
            get
            {
                if (this.ViewState["DisableSingleItem"] == null)
                {
                    this.ViewState["DisableSingleItem"] = true;
                }
                return (bool)this.ViewState["DisableSingleItem"];
            }
            set
            {
                this.ViewState["DisableSingleItem"] = value;
            }
        }
 
        [Description("Excludes the values specified from list."), Category("Loading")]
        public string ExcludedValueList
        {
            get
            {
                return (string)this.ViewState["ExcludedValueList"];
            }
            set
            {
                this.ViewState["ExcludedValueList"] = value;
            }
        }
	
		#endregion
 
	}
}
[+][-]05/05/09 07:55 PM, ID: 24311008

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zones: Programming for ASP.NET, Microsoft Visual C#.Net, C# Programming Language
Tags: dropdownlist postback
Sign Up Now!
Solution Provided By: M3mph15
Participating Experts: 1
Solution Grade: A
 
 
 
Loading Advertisement...
20090824-EE-VQP-74 - Hierarchy / EE_QW_EXPERT_20070906