how to store multiple datatable into a single dataset - c#

I have multiple datatable. I want to show all the datatable rows into a single gridview.
How can I do that?
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
DataSet ds= new DataSet();
ds.Tables.Add(dtbag101);
ds.Tables.Add(dtwallet111);
GridView1.DataSource= ds;
GridView1.DataBind();
The column names for both datatable are the same.
Here I was trying to use dataset but only first DataTable i.e. datbag101 was showing in the gridview.
How can I show all the values in one gridview?

Provided that your two data tables have the same columns, you can UNION them with some handy LINQ.
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
var result = dtbag101.AsEnumerable().Union(dtwallet111.AsEnumerable());
GridView1.DataSource = result;
GridView1.DataBind();
Otherwise try use DataTable.Merge:
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111, true);
GridView1.DataSource = dtbag101;
GridView1.DataBind();
I'm not sure why this isn't working for you. Try this method (grabbed from here):
public static DataTable Union(DataTable First, DataTable Second)
{
//Result table
DataTable table = new DataTable("Union");
//Build new columns
DataColumn[] newcolumns = new DataColumn[First.Columns.Count];
for(int i=0; i < First.Columns.Count; i++)
{
newcolumns[i] = new DataColumn(
First.Columns[i].ColumnName, First.Columns[i].DataType);
}
table.Columns.AddRange(newcolumns);
table.BeginLoadData();
foreach(DataRow row in First.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
foreach(DataRow row in Second.Rows)
{
table.LoadDataRow(row.ItemArray,true);
}
table.EndLoadData();
return table;
}
Call the method with your two datatables:
GridView1.DataSource = Union(dtbag101, dtwallet111);

You can simply use DataTable.Merge method
DataTable dtbag101 = (DataTable)Session["bag101"];
DataTable dtwallet111 = (DataTable)Session["wallet111"];
dtbag101.Merge(dtwallet111); //Merge action
GridView1.DataSource= dtbag101;
GridView1.DataBind();
I dont know much about this. Just referred it now.
or else
try for loop
DataSet ds = new DataSet();
addTables(dtbag101);
addTables(dtwallet111); //ds will be merge of both tables here
private void addTables(DataTable dt)
{
for(int intCount = ds.Tables[0].Rows.Count; intCount < dt.Rows.Count;intCount++)
{
for(int intSubCount = 0;intSubCount < dt.Columns.Count; intSubCount++)
{
ds.Tables[0].Rows[intCount][intSubCount] = dt.Rows[intCount][intSubCount];
}
}
}

You may need to use DataTable.Merge
DataTable dtAll = new DataTable();
dtAll = dtbag101 .Copy();
dtAll.Merge(dtwallet111, true);
GridView1.DataSource= dtAll;
GridView1.DataBind();
Edit to show how it should work
private void BindGridWithMergeTables()
{
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("ID");
dt2.Columns.Add("ID");
DataRow dr1 = dt1.NewRow();
DataRow dr2 = dt2.NewRow();
dr1["ID"] = "1";
dr2["ID"] = "2";
dt1.Rows.Add(dr1);
dt2.Rows.Add(dr2);
DataTable dtAll = new DataTable();
dtAll = dt1.Copy();
dtAll.Merge(dt2, true);
dataGridView1.DataSource = dtAll;
dataGridView1.DataBind();
}

Related

How to add rows to datagridview while datagridview is bind

I have a datagridview and I filled with data.
DataTable table = new DataTable();
dataGridView1.DataSource = table;
con = new SqlDataAdapter("SELECT * FROM TABLE "'", con);
ds = new System.Data.DataSet();
con .Fill(ds, "TABLE");
My problem is I have to add rows manually like the code below but it is just add one row.But what I need foreach's count row.
foreach (var a in names.Split(new char[] { ';' }))
{
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
dataGridView2.Rows[i + 1].Cells[3].Value = a.ToString();
i = i +1;
}
Try to use
DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);

Data Table Copy not showing properly in GridView

I have a stored procedure which actually concatenates 2 columns and returns a DataTable.
Its as below:
create procedure [dbo].[spEnqIDFyYear]
as
begin
select CONVERT(nvarchar(50),enq_id)+'/'+CONVERT(nvarchar(50),YEAR(fy_year)) as EnqIDFyYear from Sample.dbo.enquiry_details
end
GO
The output is as follows:
EnqIDFyYear
1/2015
2/2014
I have another procedure, whose output is as below:
profile_name
ProfileA
ProfileB
I bind both the procedures to 2 DataTables, merge those 2 DataTables into a 3rd one and bind the resulting DataTable to the gridview.
But the gridview is not showing as proper. It shows as below:
The rows should be aligned to each other. How to achieve it?
Code behind is as below:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt1 = PopulateDashBoardGrid1();
DataTable dt2 = PopulateDashBoardGrid2();
DataTable dt3 = new DataTable();
dt3 = dt1.Copy();
dt3.Merge(dt2);
GridView1.DataSource = dt3;
GridView1.DataBind();
}
//Populate the main DashBoard Grid
public DataTable PopulateDashBoardGrid1()
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("spEnqIDFyYear", con);
DataTable dt = new DataTable();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
}
public DataTable PopulateDashBoardGrid2()
{
using (SqlConnection con = new SqlConnection(cs))
{
SqlDataAdapter da = new SqlDataAdapter("spClientProfileName", con);
DataTable dt = new DataTable();
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
return dt;
}
}
Experts please help.
Regards
Anurag
You are getting that kind of output, because Merge works in that way if the columns are not same of two datatables. So you need to write some custom code.
Here is what I have:-
static DataTable MergeDataTables(DataTable dt1, DataTable dt2)
{
DataTable dt3 = dt1.Copy();
foreach (DataColumn dc in dt2.Columns)
{
dt3.Columns.Add(dc.ColumnName).DataType = dc.DataType;
}
for (int i = 0; i < dt3.Rows.Count; i++)
{
foreach (DataColumn dc in dt2.Columns)
{
string col = dc.ColumnName;
dt3.Rows[i][col] = dt2.Rows[i][col];
}
}
return dt3;
}
You can call this method to merge both datatables.

How i can read xml into DataTable type object?

I don't have problem if i read xml to DataSet:
DataSet temp = new DataSet();
temp.ReadXml(UncompressedStream, System.Data.XmlReadMode.Auto);
But if i use DataTable:
DataTable temp = new DataTable();
temp.ReadXml(UncompressedStream);
then datatable not load data (count of columns and rows equal 0 )
How i can read xml to DataTable
My temporary solution:
DataSet temp = new DataSet();
DataTable structure = new DataTable();
temp.ReadXml(UncompressedStream, System.Data.XmlReadMode.Auto);
structure = temp.Tables[0];
private static void DemonstrateReadWriteXMLDocumentWithString()
{
DataTable table = CreateTestTable("XmlDemo");
PrintValues(table, "Original table");
string fileName = "C:\\TestData.xml";
table.WriteXml(fileName, XmlWriteMode.WriteSchema);
DataTable newTable = new DataTable();
newTable.ReadXml(fileName);
// Print out values in the table.
PrintValues(newTable, "New table");
}
private static DataTable CreateTestTable(string tableName)
{
// Create a test DataTable with two columns and a few rows.
DataTable table = new DataTable(tableName);
DataColumn column = new DataColumn("id", typeof(System.Int32));
column.AutoIncrement = true;
table.Columns.Add(column);
column = new DataColumn("item", typeof(System.String));
table.Columns.Add(column);
// Add ten rows.
DataRow row;
for (int i = 0; i <= 9; i++)
{
row = table.NewRow();
row["item"] = "item " + i;
table.Rows.Add(row);
}
table.AcceptChanges();
return table;
}
This is from: microsoft - xml - datatable
Check that in this code, they add a name for the table, and create the rows and the columns.
LINQ to XML may be a thing you are rather looking for.

Convert datatable to datareader

For Performance improvement I want to convert datatable to datareader. I can not do that through query. So is there any other way to do so?
I know this is old, but the answers here seem to have missed the point of the OPs question.
DataTables have a method called CreateDataReader which will allow you to convert a DataTable to a DbDataReader object. In this case a DataTableReader.
DataTable table = new DataTable();
//Fill table with data
//table = YourGetDataMethod();
DataTableReader reader = table.CreateDataReader();
I should point out that this will not increase performance since you should be using one or the other.
Here are some more resources on the matter:
DataReader Vs DataTable
Is datareader quicker than dataset when populating a datatable?
For example
public DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
DataTable datatable = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();
try
{
foreach (DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = myRow.GetType();
myDataColumn.ColumnName = myRow[0].ToString();
datatable.Columns.Add(myDataColumn);
}
while (dataReader.Read())
{
DataRow myDataRow = datatable.NewRow();
for (int i = 0; i < schemaTable.Rows.Count; i++)
{
myDataRow[i] = dataReader[i].ToString();
}
datatable.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
return datatable;
}
catch (Exception ex)
{
Error.Log(ex.ToString());
return datatable;
}
}
Use DataTable constructor,
DataTable table = new DataTable();
//Fill table with data
DataTableReader reader = new DataTableReader(table);
Good Look!
public DataTable GetTable(IDataReader _reader)
{
DataTable dataTable1 = _reader.GetSchemaTable();
DataTable dataTable2 = new DataTable();
string[] arrayList = new string[dataTable1.Rows.Count];
for (int i = 0; i < dataTable1.Rows.Count; i++)
{
DataColumn dataColumn = new DataColumn();
if (!dataTable2.Columns.Contains(dataTable1.Rows[i]["ColumnName "].ToString()))
{
dataColumn.ColumnName = dataTable1.Rows[i]["ColumnName "].ToString();
dataColumn.Unique = Convert.ToBoolean(dataTable1.Rows[i]["IsUnique "]);
dataColumn.AllowDBNull = Convert.ToBoolean(dataTable1.Rows[i]["AllowDBNull "]);
dataColumn.ReadOnly = Convert.ToBoolean(dataTable1.Rows[i]["IsReadOnly "]);
dataColumn.DataType = (Type)dataTable1.Rows[i]["DataType "];
arrayList[i] = dataColumn.ColumnName;
dataTable2.Columns.Add(dataColumn);
}
}
dataTable2.BeginLoadData();
while (_reader.Read())
{
DataRow dataRow = dataTable2.NewRow();
for (int j = 0; j < arrayList.Length; j++)
{
dataRow[arrayList[j]] = _reader[arrayList[j]];
}
dataTable2.Rows.Add(dataRow);
}
_reader.Close();
dataTable2.EndLoadData();
return dataTable2;
}

add data to DataGrid View through DataSet?

I have a datagridview that is bound to a dataset
I defined the table and the columns, how I can programmaticlly insert data to it?
I did this
http://msdn.microsoft.com/en-us/library/5ycd1034%28VS.71%29.aspx
but it did not show the data in my DataGridView !!!
now you need to assign the values to the datagridview
DataTable dt = new DataTable();
// Add rows to dt
datagridview.DataSource = dt;
Sample example
SqlDataAdapter da = new SqlDataAdapter(quryString, con);
DataSet ds = new DataSet();
da.Fill(ds, "Emp");
//dataGridView1.DataSource = ds.Tables["Emp"];
dataGridView1.Columns.Add("EmpID", "ID");
dataGridView1.Columns.Add("FirstName", "FirstName");
dataGridView1.Columns.Add("LastName", "LastName");
int row = ds.Tables["Emp"].Rows.Count - 1;
for (int r = 0; r<= row; r++)
{
dataGridView1.Rows.Add();
dataGridView1.Rows[r].Cells[0].Value = ds.Tables["Emp"].Rows[r].ItemArray[0];
dataGridView1.Rows[r].Cells[1].Value = ds.Tables["Emp"].Rows[r].ItemArray[1];
dataGridView1.Rows[r].Cells[2].Value = ds.Tables["Emp"].Rows[r].ItemArray[2];
}
it can be bounded directly by .
DataSet ds = new DataSet();
in C#
DataGridView.DataSource = ds.Tables["your Table index which you want to bind with datagridview"];
Like
DataGridView.DataSource = ds.Tables[0];
In VB
DataGridView.DataSource = ds.Tables("your Table index which you want to bind with datagridview")
like
DataGridView.DataSource = ds.Tables(0)

Categories

Resources