读书人

求ASP.net中TextBox控件序列化的正确方

发布时间: 2012-02-04 15:43:08 作者: rapoo

求ASP.net中TextBox控件序列化的正确方法!
先看了builder.com.cn上的一篇文章
http://www.builder.com.cn/2006/1224/347743.shtml
但是XmlSerializer serializer = new XmlSerializer(typeof(TextBox));
这一句会出错。

后来又看了MSDN上的一篇文章http://www.microsoft.com/china/msdn/archives/library/dndotnet/html/objserializ.asp

自己改了一下代码,自定义继承了一个TextBox

[Serializable]
public class XMLTextBox : TextBox,ISerializable
{
public XMLTextBox() :base()
{

}

protected XMLTextBox(SerializationInfo info, StreamingContext context)
{
UnitConverter uc = new UnitConverter();
ID = info.GetString( "ID ");
Attributes.Add( "name ", info.GetString( "Name "));
TextMode = (TextBoxMode)info.GetInt32( "TextMode ");
Width = (Unit)uc.ConvertFromInvariantString(info.GetString( "Width "));
Height = (Unit)uc.ConvertFromInvariantString(info.GetString( "Height "));

}


#region ISerializable 成员

public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue( "ID ",this.ID);
info.AddValue( "Name ", this.Attributes[ "name "]);
info.AddValue( "TextMode ", this.TextMode);
info.AddValue( "Width ", this.Width.ToString());
info.AddValue( "Height ",this.Height.ToString());
}


#endregion
}

但是XmlSerializer serializer = new XmlSerializer(typeof(TextBox));这一句仍然出错!
改用MSDN上那个IFormatter和流的方法
//初始化TextBox控件
UnitConverter uc = new UnitConverter();


XMLTextBox tb = new XMLTextBox();
tb.Width = (Unit)uc.ConvertFromInvariantString( "10 ");
tb.Height = (Unit)uc.ConvertFromInvariantString( "20 ");
tb.TextMode = TextBoxMode.MultiLine;
tb.Attributes.Add( "name ", "MyTextBox ");
//序列化
IFormatter formatter = new SoapFormatter();
Stream stream = new MemoryStream();
formatter.Serialize(stream, tb);
StreamReader sr = new StreamReader(stream);
string str = sr.ReadToEnd();

Response.Write(str);
sr.Close();
stream.Close();
我这个是在.aspx页面上做的测试,为什么str取不到任何值呢?

[解决办法]
你要把TextBox对象object序列化成byte
反序列化把byte转换成object as TextBox

读书人网 >asp.net

热点推荐