Tuesday, July 3, 2007

Create DataSet

I always wanted to create the DataSet manually, without having to fill the DataSet from the DataAdapter.

The example is to get all 12 months, this is how the DataSet looks like:
This is how I did it:

public static DataSet GetAllMonths()
//Create new DataSet
DataSet dsMonth = new
DataSet ();
//Create new DataTable
DataTable dtMonth =
new DataTable ("Month");
//Create two DataColumns: Id & Month
DataColumn dcMonth =
new DataColumn ("Month");
DataColumn dcId = new DataColumn ("Id");

//Add the columns to the DataTable

//Add the 12 months to the DataTable
_AddMonthToDataTable(ref dtMonth, 1, "January");
ref dtMonth, 2, "February");
ref dtMonth, 3, "March");
ref dtMonth, 4, "April");
ref dtMonth, 5, "May");
ref dtMonth, 6, "June");
ref dtMonth, 7, "July");
ref dtMonth, 8, "August");
ref dtMonth, 9, "September");
ref dtMonth, 10, "October");
ref dtMonth, 11, "November");
ref dtMonth, 12, "December");

//Add the DataTable to DataSet

return dsMonth;

private static void _AddMonthToDataTable(
ref DataTable dt, int id, string month)
//Create new DataRow to the DataTable
DataRow dr = dt.NewRow();
//Assign values to the data columns
dr["Id"] = id;
dr["Month"] = month;
//Add the DataRow to the DataTable

No comments:

Post a Comment