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
dtMonth.Columns.Add(dcId);
dtMonth.Columns.Add(dcMonth);
//Add the 12 months to the DataTable
_AddMonthToDataTable(ref dtMonth, 1, "January");
_AddMonthToDataTable(ref dtMonth, 2, "February");
_AddMonthToDataTable(ref dtMonth, 3, "March");
_AddMonthToDataTable(ref dtMonth, 4, "April");
_AddMonthToDataTable(ref dtMonth, 5, "May");
_AddMonthToDataTable(ref dtMonth, 6, "June");
_AddMonthToDataTable(ref dtMonth, 7, "July");
_AddMonthToDataTable(ref dtMonth, 8, "August");
_AddMonthToDataTable(ref dtMonth, 9, "September");
_AddMonthToDataTable(ref dtMonth, 10, "October");
_AddMonthToDataTable(ref dtMonth, 11, "November");
_AddMonthToDataTable(ref dtMonth, 12, "December");
//Add the DataTable to DataSet
dsMonth.Tables.Add(dtMonth);
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
dt.Rows.Add(dr);
}
No comments:
Post a Comment