Creating a Method to Return a DataSet in C#

In this tutorial, we’ll show how to create a method, within your ASP.Net code, which returns a Dataset, using C#. To demonstrate this, we’ll be using the Northwind database, which is easily accessible, if you don’t already have it available in your SQL Server. We created a Gridview on our ASP.Net page and used the ‘Rainy Day’ formatting option:


 <asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3"
GridLines="Vertical">
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="#DCDCDC" />
</asp:GridView>

Then, in our code, we created the method, which returns a dataset:


private DataSet getData()
        {
// get the connection string
String conn = ConfigurationManager.ConnectionStrings["NW"].ConnectionString;
// build our SQL Select statement (should preferably be a stored procedure)
String mySQL = "Select ProductName, QuantityPerUnit, UnitPrice from Products where CategoryID=1";
DataSet ds;
using (SqlDataAdapter da = new SqlDataAdapter(mySQL, conn))
{
ds = new DataSet();
 da.Fill(ds, "ProductInfo");
}
return ds; // 'returns' the dataset
}

All that is left is to consume, or use the getData() method, to add the data to the Gridview, in some event on the page:


//consume the 'returned' dataset in the Gridview:
GridView1.DataSource = getData();
GridView1.DataBind();

You can do this in the Page_load event, or any other event, like a button click event, fired from the changing of a DropDownlist showing the Categories (see ‘Where’ clause in SQL statement) from the Northwind database.

Related Posts:

  • No Related Posts
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!