Creating a Method that Returns a Dataset (C#)

Posted by David Wier on 02/9/10 | Code Samples

In this code sample, 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();

 












































0 Comments

COMMENTS

Name:
URL:
Comment:

Comments are disabled for this article.