Sujeet Raman

Sujeet Raman

  • 743
  • 915
  • 334.3k

Columns and rows not adding dynamicaly in C# Datatable

Aug 30 2020 1:12 AM
I am learning about dynamic datatable creation from stored procedure results in C#, but I ran into a problem. I have a stored procedure which returns 2 tables as result, by using this table I need to create a separate datatable in C#. I am not able to dynamically add all the columns and rows in multiple data tables.
Function 1
public ExcelReportDetails createdataset()
{
DataSet ds = new DataSet();
ds = DataAdapter.SPArray2(storedProcedure);
}
Here in `ds`, I should get the dataset with all tables with values.
Function 2
public static DataSet SPArray2(string storedProcedureName)
{
DataSet Owndataset = new DataSet();
using (DataSet dataSet = ExecuteDataSet(cmd => ConfigureStoredProcCommand(cmd, storedProcedureName)))
{
Owndataset = dataSet.ToDataSet2();
}
return Owndataset;
}
Function 3
public static DataSet ToDataSet2(this DataSet dataset)
{
DataSet ownds2 = new DataSet();
for (var i = 0; i < dataset.Tables.Count; i++) //getting table count as 2. I am returning from stored procedure like key value pair.key-country,value-india
{
using (var table = dataset.Tables[i])
{
ownds2.Tables.Add( table.ToDataTable2());
}
}
return ownds2;
}
Function 4
public static DataTable ToDataTable2(this DataTable table)
{
DataTable owntable = new DataTable();
if (table.Rows.Count > 0)
{
for (var row = 0; row < table.Rows.Count; row++)
{
for (int i = 0; i < table.Columns.Count; i++)
{
owntable.Columns.Add(table.Columns[i]); // how do I add columns confused here
owntable.Rows.Add(table.Rows[row][i]); // how do I add rows confused here
}
}
}
return owntable;
}
Thanks a lot!

Answers (6)