Microsoft KB Archive/320714

= HOW TO: Create and Use a Typed DataSet by Using Visual C# .NET =

Article ID: 320714

Article Last Modified on 5/17/2007

-

APPLIES TO


 * Microsoft .NET Framework 1.1 Service Pack 1
 * Microsoft ADO.NET 1.1
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# .NET 2003 Standard Edition

-



This article was previously published under Q320714



For a Microsoft Visual Basic .NET version of this article, see 315678.

IN THIS TASK
SUMMARY
 * Requirements
 * Typed DataSets
 * Complete Code Listing (WebForm1.aspx)
 * Complete Code Listing (WebForm1.aspx.vb)
 * Verification
 * Troubleshooting

REFERENCES



SUMMARY
This article shows you how to create and use a typed DataSet in a small Web application. Typed DataSets, which inherit from the DataSet class, create first-class members of a DataSet's DataTables and DataColumns, yielding the many benefits that come with the use of strong typing.

back to the top

Requirements
The following items describe the recommended hardware, software, network infrastructure, skills and knowledge, and service packs that you have to have to complete these steps:
 * Microsoft SQL Server 6.5 (or later) with the Northwind database

Prior skills required:
 * General familiarity with Microsoft SQL Server
 * General familiarity with Microsoft Visual Studio .NET
 * General familiarity with Microsoft ADO.NET
 * General familiarity with Microsoft .NET Web Controls

back to the top

Typed DataSets
Follow these steps to create a small Web application by using Visual Studio .NET. The Web application uses a typed DataSet to display the results of an improvised SQL query in the Northwind database.  Start Visual Studio .NET. Create a new Web Application project named TDS in Visual C# .NET. Make sure that the Solution Explorer is displayed. If the Solution Explorer is not displayed, press CTRL+ALT+L. Make sure that the WebForm1.aspx file is open in the Editor window. If the file is not open, double-click WebForm1.aspx in the Solution Explorer to open the file. Under the Editor window, click Design to switch to Design view. To open the toolbox, press CTRL+ALT+X. In the toolbox, click Web Forms. Select and drag the following to the upper-left corner of the page: two rows each of a label followed by a text box (positioned to the right of each label). Under these, add a DataGrid in the same way. Click the top label. Press F4 to display the Properties window. Change the Text property to Product. Click the other label, and then change its Text property to Category .</li> To add a new DataSet to the project, press CTRL+SHIFT+A, and then click DataSet in the list of templates. Name the DataSet the following: dsProducts.xsd. Note that the file is actually an XML Schema. Click OK. You now see a pale yellow page in the Editor window.</li> To create a typed DataSet, press CTRL+ALT+S to open the Server Explorer.</li> Click Servers, click  , click SQLServers, click  , click Northwind, and then click Views.</li> Select the Northwind SQL Server view Alphabetical list of products, and then drag the view to the pale yellow DataSet page. A visual representation of the results set that is generated by the view appears on the page. To see the actual XML for the Schema file, click the XML button under the Editor window.</li> A Schema based on a SQL Server object now exists. To create and fill a typed DataSet, first you must generate the class that maps to the Schema. Right-click the Design view, and then make sure that the Generate DataSet option is selected. If it is not selected, select it. Press CTRL+S to save the Schema and generate the class.</li> To view the new typed DataSet class, click Show All Files in the Solution Explorer.</li> Expand the tree next to dsProducts.xsd. You see a dsProducts.vb file, which contains the new class mapping to the Schema. You also see a dsProducts.xsx file, which is used for tracking changes to the files.</li> To write code to display the typed DataSet, double-click directly on the Web Form (not on a Web Control). The Web Form's codebehind appears, and the insertion point is inside the Page_Load event.</li>  To include the classes that reside in the System.Data.SqlClient namespace, add the following using statement at the top of the codebehind: using System.Data.SqlClient; NOTE: The other namespaces that you have to have for this small Web application are automatically referenced in the project when you create a Web application in Visual Studio .NET.

</li>  In the Page_Load event procedure, create a Connection object by passing the connection string to the default constructor of the SqlConnection class: SqlConnection cn = new SqlConnection(&quot;server=myserver;uid=myuid;pwd=mypassword;database=northwind&quot;); </li>  Create a SqlCommand object that is then passed to the SqlDataAdapter object. Pass an improvised SQL statement and the new Connection object to the SqlCommand constructor. The former sets the CommandText property of the new SqlCommand object. You can also pass the name of a stored procedure. SqlCommand cmd = new SqlCommand(&quot;select * from [Alphabetical list of products]&quot;, cn); </li>  Create an instance of the SqlDataAdapter object, passing the new SqlCommand object to the constructor: SqlDataAdapter da = new SqlDataAdapter(cmd); </li>  Now you create the objects that are required to connect to the database and return data. The following is the code for the typed DataSet. Note that an instance of the dsProducts class is created: the class that maps to the dsProducts Schema and inherits from the DataSet class, not the generic DataSet class itself. dsProducts tds = new dsProducts; </li>  Call the Fill method of the SqlDataAdapter, passing in the typed DataSet object and the DataSet's typed DataTable TableName property: da.Fill(tds, tds.Tables[0].TableName); </li>  To set the Text property of the text box controls to the strongly typed columns in the typed DataSet's DataTable, use the following format: dsProducts.DataTableName[RowIndex].ColumnName For this sample application, the RowIndex is hard-coded to 5: TextBox1.Text = tds.Alphabetical_list_of_products[5].ProductName; TextBox2.Text = tds.Alphabetical_list_of_products[5].CategoryName; Because the Rows collection is zero-based, when the page loads, note that the text box controls display the product and category names of the item in the sixth row of the DataGrid. </li> <li> To display all of the results in the DataGrid, set the DataSource property of the DataGrid to the new typed DataSet, and call DataBind: DataGrid1.DataSource = tds; DataGrid1.DataBind; </li></ol>

back to the top

Complete Code Listing (WebForm1.aspx)
<%@ Page language=&quot;c#&quot; Codebehind=&quot;WebForm1.aspx.cs&quot; AutoEventWireup=&quot;false&quot; Inherits=&quot;TDS.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;> <asp:Label id=&quot;Label1&quot; runat=&quot;server&quot; >Label</asp:Label> <asp:DataGrid id=&quot;DataGrid1&quot; runat=&quot;server&quot; ></asp:DataGrid> <asp:TextBox id=&quot;TextBox2&quot; runat=&quot;server&quot;></asp:TextBox> <asp:TextBox id=&quot;TextBox1&quot; runat=&quot;server&quot;></asp:TextBox> <asp:Label id=&quot;Label2&quot; runat=&quot;server&quot; >Label</asp:Label> </HTML> back to the top

Complete Code Listing (WebForm1.aspx.cs)
using System.Data.SqlClient;

namespace TDS { ///   /// Summary description for WebForm1. ///  public class WebForm1 : System.Web.UI.Page {   protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.TextBox TextBox2; protected System.Web.UI.WebControls.DataGrid DataGrid1; private void Page_Load(object sender, System.EventArgs e)    { SqlConnection cn = new SqlConnection(&quot;server=localhost;uid=sa;pwd=abcd;database=northwind&quot;); SqlCommand cmd = new SqlCommand(&quot;select * from [Alphabetical list of products]&quot;, cn); SqlDataAdapter da = new SqlDataAdapter(cmd); dsProducts tds = new dsProducts;

da.Fill(tds, tds.Tables[0].TableName); TextBox1.Text = tds.Alphabetical_list_of_products[5].ProductName; TextBox2.Text = tds.Alphabetical_list_of_products[5].CategoryName;

DataGrid1.DataSource = tds; DataGrid1.DataBind;

}

#region Web Form Designer generated code override protected void OnInit(EventArgs e)   { //    // CODEGEN: This call is required by the ASP.NET Web Form Designer. //    InitializeComponent; base.OnInit(e); }   ///     /// Required method for Designer support - do not modify /// the contents of this method with the code editor. ///    private void InitializeComponent {       this.TextBox1.TextChanged += new System.EventHandler(this.TextBox1_TextChanged); this.Load += new System.EventHandler(this.Page_Load);

}   #endregion } }

back to the top

Verification
Press F5 to run the Web application. The browser displays &quot;Uncle Bob's Organic Dried Pears&quot; in the Product text box and &quot;Produce&quot; in the Category text box. A DataGrid that is filled with product information appears under the text boxes.

back to the top

Troubleshooting

 * Generic DataSets do not require that you pass a TableName when you call the Fill method. Typed DataSets, however, require this, even if you are accessing the DataSet's Table collection by indexes instead of the TableName. Failure to pass the typed DataSet's TableName throws a &quot;There is no Row at Position 0&quot; error at runtime. This requirement of typed DataSets also means that you cannot make up your own TableName but you must pass the one that is referenced in the typed DataSet class, which is accessed as in the preceding code.
 * Any manual changes that you make to the Schema that is generated by Visual Studio .NET are overwritten if you change the database object that you used initially to generate the Schema and typed DataSet class and drag it again to the Schema's Design view. It is generally preferable to make the changes that you have to at the Microsoft SQL Server level and to generate a new typed DataSet than to change the resultant Schema.

back to the top

<div class="references_section">