Wednesday, May 5, 2010

Creating a Strongly Typed DataSet in Asp.Net

Strongly typed DataSets are merely generic DataSets that have their columns and tables defined in advance, so the compiler already knows what they will contain. 

1.     Open Visual Studio, and create a new ASP.NET web site.
2.     In Solution Explorer, right-click to add a new item, and select DataSet. Visual Studio will recommend placing the DataSet file inside the App_Code folder, which you should allow it to do for you.
3.     The DataSet1.xsd will open in design mode, and the TableAdapter Configuration Wizard will be launched. For now, just click Cancel, because you will add tables by dragging them from the Server Explorer.
4.     Locate the Server Explorer Toolbox, navigate to your SQL Server 2005 database,
5.     Drag the dbo.empuserdetails table to your DataSet Designer window. The window should now resemble Figure.
    
                  As you can see from Figure 1, for each table that is added to the designer, Visual Studio creates a strongly  typed DataTable and a TableAdapter. The DataTable has all of its columns already defined. The table adapter is the object you will use to fill the table. By default, you have a Fill() method that will find every row from that table.
This strongly typed DataSet, as is, will return all of the records in the Product table. 
Since the Empuser table contains a lot of information, let us modify the default query to return only the employee that belong to the given empid. To do this, right-click the empuserdetailsTableAdapter and select Add Query. Pick Use SQL statements and click the Next button. Then, choose SELECT, which returns rows, and click Next. Finally, enter the following query in the window 

SELECT Empid, Username, Password 
FROM dbo.Empuserdetails
Where Empid= @Empid

Place a GridView in default.aspx
The Code in Default.aspx.cs is given below
 
public partial class _Default : System.Web.UI.Page 
{
  protected void Page_Load(object sender, EventArgs e)
  {
  DataSet1TableAdapters.EmpuserdetailsTableAdapter adas=
         new DataSet1TableAdapters.EmpuserdetailsTableAdapter ();
DataSet1.EmpuserdetailsDataTable table=adas.GetData();
                                                              //or GetDataBy(1)
 GridView1.DataSource=table;
 GridView1.DataBind();
   }
}