【原创】在asp.net中做自定义控件时属性值无法保存
写了一个组合控件,是一个按钮。
public class Button : System.Web.UI.WebControls.Button
有一个属性原先是这么写的
private EnumButtonType _buttontype = EnumButtonType.Add;
/// <summary>
/// 设置按钮类型
/// </summary>
public EnumButtonType ButtonType
{
get { return _buttontype; }
set { _buttontype = value; }
}
在运行过程中,后台代码把这个属性设成EnumButtonType.Save。结果当触发事件回发后,该属性变回默认值EnumButtonType.Add了。
要修正这个问题也简单,在定义该属性的时候,用ViewState去保存它的值。
/// <summary>
/// 设置按钮类型
/// </summary>
public EnumButtonType ButtonType
{
get { return (EnumButtonType)ViewState["ButtonType"]; }
set { ViewState["ButtonType"] = value; }
}