At times you want to return the default to show in an asp:DropDownList from the DataSource. Normally you have only two items:
- DataTextField
- DataValueField.
I will illustrate how you can add and use a DataDefaultField (boolean) to select a specific item without needing to do any C# in the page.
The steps are:
- Create a class that inherits from DropDownList
- Add in two private variable, defaultValue, isPostBack
- public class DropDownList : System.Web.UI.WebControls.DropDownList
- {
- private string defaultValue;
- private bool isPostback ;
- Do an override as shown below to detect PostBacks
Code Snippet- protected override void RaisePostDataChangedEvent()
- {
- isPostback = true;
- base.RaisePostDataChangedEvent();
- }
- Add a new Property
Code Snippet- public virtual string DataDefaultField { get; set; }
- Add another override (this picks up the (last) default value from the data.
Code Snippet- protected override void PerformDataBinding(IEnumerable data)
- {
- if (string.IsNullOrWhiteSpace(DataDefaultField))
- {
- DataDefaultField = "default";
- }
- foreach (var dataItem in data)
- {
- bool isDefault;
- if (bool.TryParse(dataItem.GetProperty(DataDefaultField), out isDefault) && isDefault)
- {
- defaultValue = dataItem.GetProperty(DataValueField);
- }
- }
- base.PerformDataBinding(data);
- }
- Add the last override which sets the default value IF it is not a postback
- public override void RenderControl(HtmlTextWriter writer)
- {
- if (! isPostback && !string.IsNullOrWhiteSpace(defaultValue))
- {
- var defaultItem = Items.FindByValue(defaultValue);
- if (defaultItem != null)
- {
- SelectedIndex = -1;
- defaultItem.Selected = true;
- }
- }
- base.RenderControl(writer);
- }
Code Snippet
Code Snippet
That’s it. You can now set the default value in the datasource.
Oops.. Bill just pointed out that I used extensions that I did not include.. Here there are:
Code Snippet
- public static string GetProperty(this object dataItem, string field, string defaultValue)
- {
- if (string.IsNullOrWhiteSpace(field))
- {
- return defaultValue;
- }
- var props = TypeDescriptor.GetProperties(dataItem);
- if (props.Count > 0)
- {
- if (props[field] != null && null != props[field].GetValue(dataItem))
- {
- return props[field].GetValue(dataItem).ToString();
- }
- for (var i = 0; i < props.Count; i++)
- {
- if (string.Compare(props[i].Name, field, StringComparison.OrdinalIgnoreCase) == 0)
- {
- return props[i].GetValue(dataItem).ToString();
- }
- }
- }
- return null;
- }
and
Code Snippet
- public static string GetProperty(this object dataItem, string field)
- {
- return GetProperty(dataItem, field, null);
- }
No comments:
Post a Comment