Ever need to have a dropdown which allows you to have a SelectedIndex that's not in the list?
This is how to write a control to allow you to do this.
1: using System;
2: using System.Collections;
3: using System.Data;
4: using System.Web.UI.WebControls;
5: using System.Web.UI;
6: using System.ComponentModel;
7: namespace Controls {
8: public class ForgivingDropDownList : DropDownList
9: {
10: [Category("Behavior"), DefaultValue(true)]
11: public bool AllowInvalidSelectedValue
12: {
13: get { return ViewState["allowInvalid"] != null ? (bool)ViewState["allowInvalid"] : true; }
14: set { ViewState["allowInvalid"] = value; }
15: }
16:
17: public override string SelectedValue
18: {
19: get
20: {
21: return base.SelectedValue;
22: }
23: set
24: {
25: if (!AllowInvalidSelectedValue)
26: {
27: base.SelectedValue = value;
28: return;
29: }
30: if (this.Items.Count != 0)
31: {
32: if ((value == null) || (base.DesignMode && (value.Length == 0)))
33: {
34: this.ClearSelection();
35: return;
36: }
37: ListItem item = this.Items.FindByValue(value);
38: if (item == null)
39: {
40: base.SelectedValue = null;
41: return;
42: }
43: base.SelectedValue = value;
44: }
45: }
46: }
47: }
48: }
Register it in web.config
1: <pages>
2: <controls>
3: <add tagPrefix="custom" namespace="Controls" />
4: </controls>
5: </pages>
Using the dropdown
1: <Custom:ForgivingDropDownList AppendDataBoundItems="true" ID="cbo" runat="server" DataSourceID="dse" DataValueField="fldID" DataTextField="fld" SelectedValue='<%# bind("fldID") %>' >
2: </Custom:ForgivingDropDownList>
3:
Simples ;-)
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5