Microsoft KB Archive/328547

= HOW TO: Serialize Web Server Controls by Using Visual C# .NET =

Article ID: 328547

Article Last Modified on 3/29/2007

-

APPLIES TO


 * Microsoft ASP.NET 1.1
 * Microsoft ASP.NET 1.0
 * Microsoft Visual C# .NET 2003 Standard Edition
 * Microsoft Visual C# .NET 2002 Standard Edition

-



This article was previously published under Q328547



IN THIS TASK

 * SUMMARY
 * Requirements
 * Create a Class to Serialize the Properties of a Web Server Control
 * Create an ASP.NET WebForm to Test the Serializable Web Server Control
 * Test the WebForm
 * REFERENCES



SUMMARY
This step-by-step article describes how to serialize the Items property of an ASP.NET ListBox Web server control.

When you develop an ASP.NET Web application, you may want to store properties of a Web server control to a persistent storage device. By creating custom classes that extend the functionality of the standard ASP.NET Web Controls library, you can serialize public properties of a Web server control.

back to the top

Requirements

 * Microsoft .NET Framework
 * Microsoft Windows 2000 or Microsoft Windows XP
 * Microsoft Internet Information Services (IIS) 5.0 or later

back to the top

Create a Class to Serialize the Properties of a Web Server Control
This section describes how to create a class that can serialize and deserialize the Items property of a ListBox Web server control (System.Web.UI.WebControls.ListBox control):  Start Microsoft Visual Studio .NET. On the File menu, click New, and then click Project. Under Project Types, select Visual C# Projects. Under Templates, select Class Library. Name the project SerializableControls, and then click OK. By default, a class file (Class1.cs) is created and added to the project. Add a reference to System.Web.dll. To do this, follow these steps:  On the Project menu in the Visual Studio .NET IDE, click Add Reference. On the .NET tab, locate System.Web.dll, and then click Select.</li> Click OK in the Add References dialog box to accept your selections. If you receive a prompt to generate wrappers for the libraries that you selected, click Yes.</li></ol> </li> Rename the Class1.cs class file to SerialListBox.cs. To do this, right-click Class1.cs in Solution Explorer, and then click Rename. Type SerialListBox.cs, and then press ENTER.</li>  In the SerialListBox.cs file, replace the existing code with: using System; using System.Runtime.Serialization; using System.Web.UI.WebControls;

namespace SerializableControls {   [Serializable] public class SerialListBox : System.Web.UI.WebControls.ListBox, System.Runtime.Serialization.ISerializable {       public SerialListBox {       }

// Deserialization constructor public SerialListBox(SerializationInfo info, StreamingContext context) {           string strItem; string strValue;

// Obtain the list of item keys. string itemList = info.GetString(&quot;ItemList&quot;); string [] items = itemList.Split(new Char[] {';'});

// Create a new list item for each key in the ItemList. for(int nCount = 0; nCount < (items.Length - 1); nCount++) // use (items.Length - 1) due to terminating ';' delimiter {               // list item Text property strItem = items[nCount]; // list item Value property strValue = info.GetString(&quot;Item-Value-&quot; + strItem);

this.Items.Add(new System.Web.UI.WebControls.ListItem(strItem, strValue)); }       }

// Serialization function (see ISerializable) public void GetObjectData(SerializationInfo info, StreamingContext context) {           string itemList = &quot;&quot;;

foreach(ListItem item in this.Items) {               // Add a ';' delimited list of item keys using the Text property of the item. itemList += item.Text + &quot;;&quot;;

// Add a Key/Value pair to the SerializationInfo object. // Use the &quot;Item-Value-<KEY>&quot; format to distingush item-value properties // from other properties stored in the SerializationInfo object. info.AddValue(&quot;Item-Value-&quot; + item.Text, item.Value); }

info.AddValue(&quot;ItemList&quot;, itemList); }   } }                    </li> On the Build menu, click Build Solution to build the solution. Alternatively, press CTRL+SHIFT+B.</li></ol>

back to the top

Create an ASP.NET WebForm to Test the Serializable Web Server Control
<ol> In Microsoft Visual Studio .NET, click New on the File menu, and then click Project.</li> Under Projects, select Visual C# Projects. Under Templates, select ASP.NET Web Application.</li> In the Location box, replace the default name with SerializationTest. If you are using the local server, you can leave the server name as http://localhost. The resulting Location box appears as follows:

http://localhost/SerializationTest

By default, the WebForm1.aspx file is created and added to the project.</li> Add a reference to SerializableControls class library. To do this, follow these steps: <ol style="list-style-type: lower-alpha;"> On the Project menu in the Visual Studio .NET Integrated Development Environment (IDE), click Add Reference.</li> On the .NET tab, select Browse.</li> In the Open dialog box, locate the SerializableControls.dll file, click Open, and then click OK.

NOTE: The SerializableControls.dll file will be located in the Bin folder under the project folder for the class library project that you have just created.</li></ol> </li>  In the lower left corner of the Web form designer, click HTML to switch to the HTML view for WebForm1.aspx. Replace the existing code with: <%@ Register TagPrefix=&quot;cc1&quot; Namespace=&quot;SerializableControls&quot; Assembly=&quot;SerializableControls&quot; %> <%@ Page language=&quot;c#&quot; Codebehind=&quot;WebForm1.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;SerializationTest.WebForm1&quot; %> <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0 Transitional//EN&quot; > <HTML> <HEAD> WebForm1 <meta name=&quot;GENERATOR&quot; Content=&quot;Microsoft Visual Studio 7.0&quot;> <meta name=&quot;CODE_LANGUAGE&quot; Content=&quot;C#&quot;> <meta name=&quot;vs_defaultClientScript&quot; content=&quot;JavaScript&quot;> <meta name=&quot;vs_targetSchema&quot; content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot;> </HEAD> <body MS_POSITIONING=&quot;GridLayout&quot;> <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;> <cc1:SerialListBox id=&quot;lstSerListBox&quot; style=&quot;Z-INDEX: 101; LEFT: 85px; POSITION: absolute; TOP: 23px&quot; runat=&quot;server&quot; Width=&quot;172px&quot; Height=&quot;121px&quot; EnableViewState=&quot;False&quot; AutoPostBack=&quot;True&quot;> <asp:ListItem Value=&quot;1&quot;>First Item</asp:ListItem> <asp:ListItem Value=&quot;2&quot;>Second Item</asp:ListItem> <asp:ListItem Value=&quot;3&quot;>Third Item</asp:ListItem> </cc1:SerialListBox> <asp:Button id=&quot;btnLoad&quot; style=&quot;Z-INDEX: 105; LEFT: 17px; POSITION: absolute; TOP: 111px&quot; runat=&quot;server&quot; Text=&quot;Load&quot;></asp:Button> <asp:Button id=&quot;btnSave&quot; style=&quot;Z-INDEX: 103; LEFT: 16px; POSITION: absolute; TOP: 26px&quot; runat=&quot;server&quot; Text=&quot;Save&quot;></asp:Button> <asp:Label id=&quot;lblValue&quot; style=&quot;Z-INDEX: 106; LEFT: 270px; POSITION: absolute; TOP: 25px&quot; runat=&quot;server&quot; Width=&quot;68px&quot; Height=&quot;22px&quot;>Value: </asp:Label> </HTML> NOTE: When you paste code in the HTML window, paste the code segments as HTML. To do this, select Paste as HTML on the Edit menu.

This code does the following:

<ul> Adds a Button Web server control to the Web form. The ID of the control is set to btnLoad, and the Text property is set to Load.</li> Adds a Button Web server control to the Web form. The ID of the control is set to btnSave, and the Text property is set to Save.</li> Adds a Label control to the Web form.</li> <li>Adds the SerialListBox custom control with three list items. The ID is set to lstSerListBox. To use this control, you must add a reference to the top of the Web page. This defines the namespace and tag that is used in the HTML.</li></ul> </li> <li> In the lower left corner of the IDE, click Design to switch to the Design view of WebForm1.aspx. Double-click btnSave. This starts the btnSave_Click event handler in the code-behind Visual C# .NET (WebForm1.aspx.cs) file. Replace the existing code with the following: private void btnSave_Click(object sender, System.EventArgs e) { Stream stream = new FileStream(@&quot;c:\Test\MyListBox.bin&quot;,  FileMode.Create, FileAccess.Write, FileShare.None);

// Serialize the object, and close the TextWriter. BinaryFormatter formatter = new BinaryFormatter; formatter.Serialize(stream, lstSerListBox); stream.Close;

// Clear all SerialListBox items. lstSerListBox.Items.Clear; lblValue.Text = &quot;&quot;; } NOTE: In this code, C:\Test is a folder that you must create. This folder holds the file that has the properties of the Web server control. Make sure that this folder has Write permissions for the account that the ASP.NET code is running under. By default, ASP.NET applications in version 1.0 of the .NET Framework run under the ASPNET account. </li> <li> In Solution Explorer, right-click the WebForm1.aspx file, and then click View Designer to switch back to Design view for the WebForm1.aspx file. In Design view, double-click the btnLoad button. This opens the Visual C# .NET code for the btnLoad_Click event handler. Replace the existing code with the following code: private void btnLoad_Click(object sender, System.EventArgs e) { // Open the FileStream to read from. Stream stream = File.OpenRead(@&quot;C:\Test\MyListBox.bin&quot;);

// Deserialize the object, and close the TextReader. BinaryFormatter formatter = new BinaryFormatter; lstSerListBox = (SerializableControls.SerialListBox)(formatter.Deserialize(stream)); stream.Close; }                   </li> <li> Switch back to the WebForm1.aspx Design view, and then double-click the lstSerListBox list box control. This opens the Visual C# .NET code for the lstSerListBox_SelectedIndexChanged event handler. Replace the existing code with the following: private void lstSerListBox_SelectedIndexChanged(object sender, System.EventArgs e) { lblValue.Text = &quot;Value: &quot; + lstSerListBox.SelectedItem.Value.ToString; }                   </li> <li> In the WebForm1.aspx.cs file, add the following code at the top of the file to import these namespaces : using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; </li> <li>On the Build menu, click Build Solution to build the solution. Alternatively, press CTRL+SHIFT+B.</li></ol>

back to the top

Test the WebForm

 * 1) In Solution Explorer, right-click the WebForm1.aspx file, and then click View in Browser.
 * 2) When you see a Web forms page that contains a Load button, a Save button, a list box, and a label, click any item in the list box. The label control displays the value of the selected list box item.
 * 3) Click Save. The contents of the list box are serialized and saved to the disk. The contents of the list box disappear.
 * 4) Click Load. The serialized data is read from the disk and a new ListBox control is instantiated with the serialized data. The contents of the list box are restored to the previous state.

back to the top

<div class="references_section">