WebControlsExtend Source Code
1.WebControlsExtend.cs
using System;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Resources;
using System.Reflection;
namespace ElevenWolf.Web
{
/// <summary>
/// 作用:WebControls赋值取值类
/// 作者:elevenwolf
/// 日期:2004-8-15
/// </summary>
[
ProvideProperty("ColumnName",typeof(Control)),
ParseChildren(true,"Settings"),
PersistChildren(false),
DefaultProperty("Settings"),
Designer(typeof(WebControlDesigner)),
]
public class WebControlsExtend : System.Web.UI.WebControls.WebControl, IExtenderProvider
{
public WebControlsExtend()
{
}
#region 页面中控件的扩展属性
[
DefaultValue(""),
Description("实体类中的属性名称。")
]
public String GetColumnName(Control control)
{
foreach( WebControlEntity setting in this.Settings )
{
if ( control.ID == setting.ControlID )
{
return setting.ColumnName;
}
}
return String.Empty;
}
public void SetColumnName(Control control, String value)
{
if (value == null)
{
value = String.Empty;
}
WebControlEntity newSetting = null;
foreach( WebControlEntity setting in Settings )
{
if ( setting.ControlID == control.ID )
{
newSetting = setting;
break;
}
}
if ( newSetting == null )
{
if ( value != "" )
{
newSetting = new WebControlEntity();
newSetting.ControlID = control.ID;
newSetting.ColumnName = value;
this.Settings.Add( newSetting );
}
}
else
{
if ( value != "" )
{
newSetting.ColumnName = value;
}
else
{
this.Settings.Remove( newSetting );
}
}
notifyDesignerOfChange();
}
/// <summary>
/// 通知设计器控件属性已改变
/// </summary>
private void notifyDesignerOfChange()
{
if ( this.Site != null && this.Site.DesignMode )
{
try
{
IDesignerHost host = (IDesignerHost)this.Site.GetService(typeof(IDesignerHost));
if ( host != null )
{
IComponentChangeService changer = (IComponentChangeService)host.GetService(typeof(IComponentChangeService));
if ( changer != null )
{
changer.OnComponentChanged(this,null,null,null);
}
}
}
catch
{
}
}
}
/// <summary>
/// 定义哪种类型的控件可以被扩展,实现IExtenderProvider接口
/// </summary>
Boolean IExtenderProvider.CanExtend(Object target)
{
if ( target is System.Web.UI.Page ) { return false; }
if ( target is System.Web.UI.HtmlControls.HtmlForm ) { return false; }
if ( target is System.Web.UI.HtmlControls.HtmlInputButton ) { return false; }
if ( target is System.Web.UI.HtmlControls.HtmlButton ) { return false; }
if ( target is System.Web.UI.WebControls.Button ) { return false; }
if ( target is System.Web.UI.WebControls.LinkButton ) { return false; }
if ( target is System.Web.UI.WebControls.ImageButton ) { return false; }
if (target is TextBox) { return true; }
if (target is DropDownList) { return true; }
if (target is CheckBox) { return true; }
if (target is RadioButton) { return true; }
if (target is CheckBoxList) { return true; }
if (target is RadioButtonList) { return true; }
return false;
}
#endregion
#region 操作实体类
/// <summary>
/// 从实体类中获取数据
/// </summary>
/// <param name="obj">实体类</param>
public void FillData(object obj)
{
foreach(WebControlEntity setting in Settings)
{
Control control=Parent.FindControl(setting.ControlID);
Type t = obj.GetType();
PropertyInfo p;
if(control==null)
{
continue;
}
switch(control.GetType().Name.ToUpper())
{
case "TEXTBOX":
System.Web.UI.WebControls.TextBox textBox = control as System.Web.UI.WebControls.TextBox;
p = obj.GetType().GetProperty(setting.ColumnName);
object o;
o=p.GetValue(obj,null);
textBox.Text = p.GetValue(obj,null).ToString().Trim();
break;
case "DROPDOWNLIST":
DropDownList ddl = control as DropDownList;
p = t.GetProperty(setting.ColumnName);
ddl.SelectedValue = p.GetValue(obj,null).ToString().Trim();
break;
case "LISTBOX":
ListBox lb = control as ListBox;
p = t.GetProperty(setting.ColumnName);
lb.SelectedValue = p.GetValue(obj,null).ToString().Trim();
break;
case "CHECKBOX":
CheckBox cb = control as CheckBox;
p = t.GetProperty(setting.ColumnName);
if(p.GetValue(obj,null).ToString()=="1")
{
cb.Checked = true;
}
else
{
cb.Checked = false;
}
break;
case "RADIOBUTTON":
RadioButton rb = control as RadioButton;
p = t.GetProperty(setting.ColumnName);
if(p.GetValue(obj,null).ToString()=="1")
{
rb.Checked = true;
}
else
{
rb.Checked = false;
}
break;
case "CHECKBOXLIST":
CheckBoxList cbl = control as CheckBoxList;
p = t.GetProperty(setting.ColumnName);
cbl.SelectedValue = p.GetValue(obj,null).ToString().Trim();
break;
case "RADIOBUTTONLIST":
RadioButtonList rbl = control as RadioButtonList;
p = t.GetProperty(setting.ColumnName);
string str;
str=p.GetValue(obj,null).ToString().Trim();
rbl.SelectedValue = str;
break;
}
}
}
/// <summary>
/// 设置页面中的值给实体类
/// </summary>
/// <param name="obj">实体类</param>
public void SaveData(object obj)
{
foreach(WebControlEntity setting in Settings)
{
Control control=Parent.FindControl(setting.ControlID);
Type t = obj.GetType();
PropertyInfo p;
if(control==null)
{
continue;
}
switch(control.GetType().Name.ToUpper())
{
case "TEXTBOX":
System.Web.UI.WebControls.TextBox textBox = control as System.Web.UI.WebControls.TextBox;
p = obj.GetType().GetProperty(setting.ColumnName);
NullColumnException(p,setting.ColumnName);
p.SetValue(obj,GetValidateData(p.PropertyType,textBox.Text),null);
break;
case "DROPDOWNLIST":
DropDownList ddl = control as DropDownList;
p = obj.GetType().GetProperty(setting.ColumnName);
NullColumnException(p,setting.ColumnName);
p.SetValue(obj, GetValidateData(p.PropertyType,ddl.SelectedValue), null);
break;
case "LISTBOX":
ListBox lb = control as ListBox;
p = t.GetProperty(setting.ColumnName);
NullColumnException(p,setting.ColumnName);
p.SetValue(obj, GetValidateData(p.PropertyType,lb.SelectedValue), null);
break;
case "CHECKBOX":
CheckBox cb = control as CheckBox;
p = t.GetProperty(setting.ColumnName);
NullColumnException(p,setting.ColumnName);
if(cb.Checked)
{
p.SetValue(obj, 1, null);
}
else
{
p.SetValue(obj, 0, null);
}
break;
case "RADIOBUTTON":
RadioButton rb = control as RadioButton;
p = t.GetProperty(setting.ColumnName);
NullColumnException(p,setting.ColumnName);
if(rb.Checked)
{
p.SetValue(obj, 1, null);
}
else
{
p.SetValue(obj, 0, null);
}
break;
case "CHECKBOXLIST":
CheckBoxList cbl = control as CheckBoxList;
p = t.GetProperty(setting.ColumnName);
NullColumnException(p,setting.ColumnName);
p.SetValue(obj, GetValidateData(p.PropertyType,cbl.SelectedValue), null);
break;
case "RADIOBUTTONLIST":
RadioButtonList rbl = control as RadioButtonList;
p = t.GetProperty(setting.ColumnName);
NullColumnException(p,setting.ColumnName);
p.SetValue(obj, GetValidateData(p.PropertyType,rbl.SelectedValue), null);
break;
}
}
}
void NullColumnException(PropertyInfo p,string ps_name)
{
if(p==null)
{
throw new Exception("WebControlsExtend Error:实体类中没有对应的属性名!请注意大小写!"+ps_name);
}
}
private object GetValidateData(System.Type pt,string ps_value)
{
switch(pt.Name.ToUpper())
{
case "INT16":
if(ps_value.Trim()=="")
{
return 0;
}
try
{
return Convert.ToInt16(ps_value);
}
catch
{
return 0;
}
case "INT64":
if(ps_value.Trim()=="")
{
return 0;
}
try
{
return Convert.ToInt64(ps_value);
}
catch
{
return 0;
}
case "INT32":
if(ps_value.Trim()=="")
{
return 0;
}
try
{
return Convert.ToInt32(ps_value);
}
catch
{
return 0;
}
case "DOUBLE":
if(ps_value.Trim()=="")
{
return 0;
}
try
{
return Convert.ToDouble(ps_value);
}
catch
{
return 0;
}
case "DECIMAL":
if(ps_value.Trim()=="")
{
return 0;
}
try
{
return Convert.ToDecimal(ps_value);
}
catch
{
return 0;
}
case "DATETIME":
if(ps_value.Trim()=="")
{
return DateTime.Now;
}
try
{
return Convert.ToDateTime(ps_value);
}
catch
{
return DateTime.Now;
}
}
return ps_value;
}
#endregion
#region 控件实现存储
/// <summary>
/// 集合属性并显示在界面中
/// </summary>
[
DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
NotifyParentProperty(true),
PersistenceMode(PersistenceMode.InnerDefaultProperty)
]
public WebControlCollection Settings
{
get
{
if (settings == null)
{
settings = new WebControlCollection();
if (IsTrackingViewState)
{
((IStateManager)settings).TrackViewState();
}
}
return settings;
}
}
/// <summary>
/// 是否可见
/// </summary>
[
Browsable(false)
]
public override Boolean Visible
{
get { return base.Visible; }
set { base.Visible = value; }
}
protected override void OnPreRender(System.EventArgs e)
{
base.OnPreRender(e);
if ( settings == null || settings.Count == 0 )
{
return;
}
if ( PropertiesValid )
{
}
else
{
throw new HttpException("WebControlsExtend Error:有一个或多个扩展属性值没有设置 " );
}
}
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
}
#endregion
#region 检验属性
/// <summary>
/// 确保当前的属性有效
/// </summary>
protected virtual Boolean PropertiesValid
{
get
{
if (!(this.propertiesChecked))
{
this.propertiesValid = this.ControlPropertiesValid();
this.propertiesChecked = true;
}
return this.propertiesValid;
}
}
private Boolean propertiesChecked = false;
private Boolean propertiesValid = false;
protected virtual bool ControlPropertiesValid()
{
foreach( WebControlEntity setting in this.Settings )
{
// if ( FindControlInContainers( setting.ControlID ) == null || FindControlInContainers( setting.ColumnName ) == null )
if ( setting.ColumnName == null )
{
return false;
}
}
return true;
}
private Control FindControlInContainers(String controlName)
{
return this.NamingContainer.FindControl(controlName);
}
private Boolean DetermineCausesValidation( Control ColumnName )
{
System.Reflection.PropertyInfo causesVal = ColumnName.GetType().GetProperty("CausesValidation");
if ( causesVal != null )
{
return (Boolean)causesVal.GetValue(ColumnName, null);
}
else
{
return false;
}
}
#endregion
#region 页面状态管理
protected override void LoadViewState(object savedState)
{
object baseState = null;
object[] myState = null;
if (savedState != null)
{
myState = (object[])savedState;
if (myState.Length != 2)
{
throw new ArgumentException("Invalid view state");
}
baseState = myState[0];
}
base.LoadViewState(baseState);
if ((myState != null) && (myState[1] != null))
{
((IStateManager)Settings).LoadViewState(myState[1]);
}
}
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
object settingsState = null;
if ((settings != null) && (settings.Count > 0))
{
settingsState = ((IStateManager)settings).SaveViewState();
}
if ((baseState != null) || (settingsState != null))
{
object[] savedState = new object[2];
savedState[0] = baseState;
savedState[1] = settingsState;
return savedState;
}
return null;
}
protected override void TrackViewState()
{
base.TrackViewState();
if (settings != null)
{
((IStateManager)settings).TrackViewState();
}
}
#endregion Custom State Management Implementation
#region Private变量
private WebControlCollection settings;
#endregion
}
}
2.WebControlSettingControlBuilder.cs
using System;
using System.Web;
using System.Web.UI;
namespace ElevenWolf.Web
{
/// <summary>
/// 作用:生成控件类,继承ControlBuilder
/// 作者:elevenwolf
/// 日期:2004-8-15
/// </summary>
public class WebControlSettingControlBuilder : ControlBuilder
{
public WebControlSettingControlBuilder()
{
}
public override bool AllowWhitespaceLiterals()
{
return false;
}
}
}
3.WebControlEntity.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
namespace ElevenWolf.Web
{
/// <summary>
/// 作用:WebControls实体类
/// 作者:elevenwolf
/// 日期:2004-8-15
/// </summary>
[
ControlBuilder(typeof(WebControlSettingControlBuilder)),
TypeConverter(typeof(ExpandableObjectConverter))
]
public class WebControlEntity : IStateManager
{
public WebControlEntity()
{
}
[
NotifyParentProperty(true),
]
public String ControlID
{
get
{
string savedState = (string)(ViewState["ControlID"]);
return (savedState == null)? String.Empty : savedState;
}
set
{
ViewState["ControlID"] = value;
}
}
[
NotifyParentProperty(true)
]
public String ColumnName
{
get
{
string savedState = (string)(ViewState["ColumnName"]);
return (savedState == null)? String.Empty : savedState;
}
set
{
ViewState["ColumnName"] = value;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
protected StateBag ViewState
{
get
{
if (_viewState == null)
{
_viewState = new StateBag(false);
if (_isTrackingViewState) ((IStateManager)_viewState).TrackViewState();
}
return _viewState;
}
}
internal void SetDirty()
{
if (_viewState != null)
{
ICollection Keys = _viewState.Keys;
foreach (string key in Keys)
{
_viewState.SetItemDirty(key, true);
}
}
}
#region 实现IStatemanager接口
bool IStateManager.IsTrackingViewState
{
get
{
return _isTrackingViewState;
}
}
void IStateManager.LoadViewState(object savedState)
{
if (savedState != null)
{
((IStateManager)ViewState).LoadViewState(savedState);
}
}
object IStateManager.SaveViewState()
{
if (_viewState != null)
{
return ((IStateManager)_viewState).SaveViewState();
}
return null;
}
void IStateManager.TrackViewState()
{
_isTrackingViewState = true;
if (_viewState != null)
{
((IStateManager)_viewState).TrackViewState();
}
}
#endregion
private bool _isTrackingViewState;
private StateBag _viewState;
}
}
4.WebControlDesigner.cs
using System;
namespace ElevenWolf.Web
{
/// <summary>
/// 作用:控件设计器
/// 作者:elevenwolf
/// 日期:2004-8-15
/// </summary>
public class WebControlDesigner : System.Web.UI.Design.ControlDesigner
{
/// <summary>
/// Creates a new instance of the WebControlDesigner
/// </summary>
public WebControlDesigner(){}
/// <summary>
/// Overrides <see cref="System.Web.UI.Design.ControlDesigner.GetDesignTimeHtml"/>
/// </summary>
public override string GetDesignTimeHtml()
{
return this.CreatePlaceHolderDesignTimeHtml();
}
}
}
5.WebControlCollection.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing.Design;
using System.Web.UI;
namespace ElevenWolf.Web
{
/// <summary>
/// 作用:WebControls集合类
/// 作者:elevenwolf
/// 日期:2004-8-15
/// </summary>
[
Editor(typeof(System.ComponentModel.Design.CollectionEditor), typeof(UITypeEditor))
]
public sealed class WebControlCollection : IList, IStateManager
{
private ArrayList settings;
private bool _isTrackingViewState;
private bool _saveAll;
internal WebControlCollection()
{
settings = new ArrayList();
}
public WebControlEntity this[int index]
{
get
{
return (WebControlEntity)settings[index];
}
}
object IList.this[int index]
{
get
{
return settings[index];
}
set
{
settings[index] = (WebControlEntity)value;
}
}
public int Add(WebControlEntity item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
settings.Add(item);
if (_isTrackingViewState)
{
((IStateManager)item).TrackViewState();
item.SetDirty();
}
return settings.Count - 1;
}
public void Clear()
{
settings.Clear();
if (_isTrackingViewState)
{
_saveAll = true;
}
}
public bool Contains(WebControlEntity item)
{
if (item == null)
{
return false;
}
return settings.Contains(item);
}
public int IndexOf(WebControlEntity item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return settings.IndexOf(item);
}
public void Insert(int index, WebControlEntity item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
settings.Insert(index,item);
if (_isTrackingViewState)
{
((IStateManager)item).TrackViewState();
_saveAll = true;
}
}
public void RemoveAt(int index)
{
settings.RemoveAt(index);
if (_isTrackingViewState)
{
_saveAll = true;
}
}
public void Remove(WebControlEntity item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
int index = IndexOf(item);
if (index >= 0)
{
RemoveAt(index);
}
}
#region 实现IEnumerable接口
public IEnumerator GetEnumerator()
{
return settings.GetEnumerator();
}
#endregion IEnumerable Implementation
#region 实现ICollection接口
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int Count
{
get
{
return settings.Count;
}
}
public void CopyTo(Array array, int index)
{
settings.CopyTo(array,index);
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public bool IsSynchronized
{
get
{
return false;
}
}
[
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public object SyncRoot
{
get
{
return this;
}
}
#endregion ICollection Implementation
#region 实现IList接口
bool IList.IsFixedSize
{
get
{
return false;
}
}
bool IList.IsReadOnly
{
get
{
return false;
}
}
int IList.Add(object item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (!(item is WebControlEntity))
{
throw new ArgumentException("item must be a WebControlEntity");
}
return Add((WebControlEntity)item);
}
void IList.Clear()
{
Clear();
}
bool IList.Contains(object item)
{
return Contains(item as WebControlEntity);
}
int IList.IndexOf(object item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (!(item is WebControlEntity))
{
throw new ArgumentException("item must be a WebControlEntity");
}
return IndexOf((WebControlEntity)item);
}
void IList.Insert(int index, object item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (!(item is WebControlEntity))
{
throw new ArgumentException("item must be a WebControlEntity");
}
Insert(index, (WebControlEntity)item);
}
void IList.Remove(object item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
if (!(item is WebControlEntity))
{
throw new ArgumentException("item must be a WebControlEntity");
}
Remove((WebControlEntity)item);
}
void IList.RemoveAt(int index)
{
RemoveAt(index);
}
#endregion IList Implementation
#region 实现IStateManager接口
bool IStateManager.IsTrackingViewState
{
get
{
return _isTrackingViewState;
}
}
void IStateManager.LoadViewState(object savedState)
{
if (savedState == null)
{
return;
}
if (savedState is ArrayList)
{
// 获取所有的WebControlEntitys到view state中.
_saveAll = true;
ArrayList states = (ArrayList) savedState;
settings = new ArrayList(states.Count);
for (int i = 0; i < states.Count; i++)
{
WebControlEntity setting = new WebControlEntity();
Add(setting);
((IStateManager)setting).LoadViewState(states[i]);
}
}
else
{
// 加载所有的WebControlEntitys.
Pair p = (Pair) savedState;
ArrayList indices = (ArrayList)p.First;
ArrayList states = (ArrayList)p.Second;
for (int i = 0 ; i < indices.Count; i++)
{
int index = (int)indices[i];
if (index < this.Count)
{
((IStateManager)settings[index]).LoadViewState(states[i]);
}
else
{
WebControlEntity setting = new WebControlEntity();
Add(setting);
((IStateManager)setting).LoadViewState(states[i]);
}
}
}
}
void IStateManager.TrackViewState()
{
_isTrackingViewState = true;
foreach (WebControlEntity setting in settings)
{
((IStateManager)setting).TrackViewState();
}
}
object IStateManager.SaveViewState()
{
if (_saveAll == true)
{
// 保存所有的WebControlEntity.
ArrayList states = new ArrayList(Count);
for (int i = 0; i < Count; i++)
{
WebControlEntity setting = (WebControlEntity)settings[i];
setting.SetDirty();
states.Add(((IStateManager)setting).SaveViewState());
}
if (states.Count > 0)
{
return states;
}
else
{
return null;
}
}
else
{
ArrayList indices = new ArrayList();
ArrayList states = new ArrayList();
for (int i = 0; i < Count; i++)
{
WebControlEntity setting = (WebControlEntity)settings[i];
object state = ((IStateManager)setting).SaveViewState();
if (state != null)
{
states.Add(state);
indices.Add(i);
}
}
if (indices.Count > 0)
{
return new Pair(indices, states);
}
return null;
}
}
#endregion IStateManager Implementation
}
}
建一个类工程,把这5个cs文件添加到工程中就可以了。