How to transfer a DataTable between pages - c#

I have a DataTable at page1.aspx and want page2.aspx to read and storage that DataTable so i can freely use this one too.
There is a simple way to do that?
It's only for a college homework so nothig too big or complicated, only a DataTable with simple items.

you can use a Session variable
in page1 code behind
Session["dt1"] = dtFullGrid;
in page2 code behind
GridView1.DataSource = Session["dt1"];
GridView1.DataBind();
or
Datatable dt2 = new Datatable();
dt2 = (DataTable)Session["dt1"];

#NorbertoEscobar offered good solution, but you may use Class to do that. In class you have some function, that will return datatable, or have datatable as it is.
DataTable dt = YourClass.GetMyDataTable();
Or void function:
DataTable dt = new DataTable();
YourClass.FillMyDataTable(dt);

Related

select top N rows from Datatable C# Windows form application

I am using following code to select top 1000 rows from Datatable dt_Customers and update it with this selection. Every thing is working fine.
DataTable dt = new DataTable();
dt = dt_Customers.Rows.Cast<System.Data.DataRow>().Take(1000).CopyToDataTable();
I am not sure this is the right way or not? Is there any other way to achieve this or I am going fine ?
Thanks.
You don't need to instantiate new DataTable and assign it to dt variable. Also you can use AsEnumerable() extension:
DataTable dt = dt_Customers.AsEnumerable().Take(1000).CopyToDataTable();

"DataTable already belongs to another DataSet"

I can't figure out why I am getting a "DataTable already belongs to another DataSet" exception.
Here is my code:
DataSet AlertSet = new DataSet();
DataTable generalAlertData = new DataTable("GeneralAlertData");
generalAlertData = //function that returns datatable
//throws exception
AlertSet.Tables.Add(generalAlertData)
When is another dataset being created and when is the generalAlertData datatable being added to it?
I tried using a slightly different syntax to create and add the table and got the same error:
DataSet AlertSet = new DataSet();
DataTable generalAlertData = //function that returns datatable
//throws exception
AlertSet .Tables.Add(generalAlertData);
It depends on what your function that retrieve the datatable does.
If that function use a DataAdapter and fills a dataset then you have the DataSet property of the table automatically assigned and you need to remove it before assigning a different DataSet
You could try this to remove the original DataSet and use your own
DataTable generalAlertData = GetTable();
DataSet u = generalAlertData.DataSet;
u.Tables.Remove(generalAlertData.TableName);
AlertSet.Tables.Add(generalAlertData);
So, if your hypothetical GetTable works in this way
public DataTable GetTable()
{
...
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds.Tables[0];
}
then you have the DataSet assigned to the returned datatable.
Instead this code doesn't assign anything to the DataSet property
public DataTable GetTable()
{
...
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}
The DataTable returned from the method call, was added to a DataSet. Make sure it's not added to a DataSet; just build a stand alone DataTable.
As a side-note, returning a DataTable from a method call that assigns to this one makes the line above it irrelevant (the new).
This is an old question now but maybe this answer will help others.
I too received this error. I looked through my source code, found literally no other datasets and was puzzled as to why this was happening.
The solution to my issue was in my data access library. It didn't have a "getDataTable" routine but I did have a getDataset routine. When I needed just a datatable I called getDataset and took the tables(0) datatable instance.
The end result of this is that I got back my datatable like I wanted, but the datatable was already part of the dataset returned from my data access call. Thus, the error.
I had to add a getDatatable routine into my data access library to eliminate this problem.
I had the same problem and I solved it using Remove. In my opinion, your code could be this:
DataSet AlertSet = new DataSet();
DataTable generalAlertData = new DataTable("GeneralAlertData");
AlertSet.Tables.Add(generalAlertData);
AlertSet.Tables.Remove(generalAlertData);
Please, let me know if this code works.
My working code was like this:
DataTable myTable = new DataTable();
private void Save()
{
DataSet myDataSet = new DataSet();
myDataSet.Tables.Add(myTable);
myDataSet.Tables.Remove(myTable);//This works
myDataSet.WriteXml("myTable.xml");
}
private void buttonSave_Click(object sender, EventArgs e)
{
Save();
}
Every time I clicked the button buttonSave, the message “DataTable already belongs to another DataSet" appeared. After writing the line code myDataSet.Tables.Remove(myTable);//This works the application started running without problems and now I can click the button more times, without losing the value of myTable and without the error message.
I hope this can help.

How to get an underlying DataTable from a control (i.e. under DataGridView)?

dataGridView1.DataSource = myDataSet1;
dataGridView1.DataMember = "SomeTable";
And now I want to get the refference to DataTable back from my dataGridView1.
Something like this:
DataTable dt = (DataTable)dataGridView1.DataSource... ;
I'm aware of BindingContext, but couldn't find the way to get DataTable refference back.
Got it.
DataSet dataSet = (DataSet)dataGridView1.DataSource;
string tableName = dataGridView1.DataMember;
DataTable dt =dataSet.Tables[tableName];
you are assigning Dataset as datasource to your gridview. So, the line below would help u.
DataTable dt = ((DataSet)dataGridView1.DataSource).Tables[index];
Assuming that you have only one datatable in your dataset. you can also use your table name instead of index.
You can convert it in this way
BindingSource bs = (BindingSource )dgrid.DataSource;
DataTable tCxC = (DataTable ) bs.DataSource
Look at this question How can I export a GridView.DataSource to a datatable or dataset?
You can either be resilient (to avoid null error) or take a chance.
The short version is:
DataTable dt = ((DataSet) dataGridView1.DataSource).Tables[0];
A more resilient approach (not assuming the view is bound to a DataSet):
DataSet ds = dataGridView1 as DataSet;
if (ds != null) DataTable dt = ds.Tables[0];
Obviously you can inspect/check the number of tables in the DataSet.

DataTable From Session Memory has No Columns

Im trying to retrieve a datatable that I put into a session variable, however when i do it apears that there are no columns...
I have done this before in VB.NET, I'n now using C#, and it worked perfectly, and as far as i can see there is no change in the code other than the obvious syntax changes.
EDIT:
The dt (in part 2) variable has the right data when i look in the data visulization window, but i have noticed that the other properties associated with a datatable are abscent. When i hover over a normal looking datatable with my mouse it looks like the following: " dt ----- {System.Data.DataTable}" but in the class im working on it just looks like "dt ----- {}". Also, after I return the session variable into the dt I clone it (dtclone = dt.clone(); ) and the clone is empty in the data visulizer.... what on earth!
EDIT 2:
I have now also tried converting the first datatable to a dataset, putting this in the session variable, and recoverting it back to a datatable in the class.
Am starting to wonder if it is a probelm with:
dt.Load(sqlReader);
The data does appear after this step though in the dataset visualiser, but not after being cloned.
Code below.
All help very welcome!
Thanks in advance
Chris
1) SQL command in a webhandler, the results of which populate the datatable to be put into the session variable.
DataTable dt = new DataTable();
SqlDataReader sqlReader= default(SqlDataReader);
SqlDataAdapter sqlAdapter = new SqlDataAdapter();
sqlReader = storedProc.ExecuteReader(CommandBehavior.CloseConnection);
dt.Load(sqlReader);
System.Web.HttpContext.Current.Session["ResultsTable"] = dt;
2) Part of the code in a class which performs calculations on the table:
DataTable dt = (DataTable)HttpContext.Current.Session["ResultsTable"];
did you call DataTable dispose after setting Session Var?
Because if you do this, solution is like this:
System.Web.HttpContext.Current.Session["ResultsTable"] = dt.Copy();

Creating a DataTable object with dummy data

I am trying to databind a DataTable to an accordion and I have found that If I retrieve the DataTable from a database using a table adapter it binds to the accordion perfectly however what I want to do is create a dummy table (for testing purposes if I don't have access to my database) the code to create the dummy table is below:
DataTable table2 = new DataTable("articletable");
table2.Columns.Add("articleID");
table2.Columns.Add("title");
table2.Columns.Add("content");
DataRow row = table2.NewRow();
row[0] = "1";
row[1] = "article name";
row[2] = "article contents go here";
table2.Rows.Add(row);
When I try to data bind that table however the accordion does not display. I can bind it to a gridview or detailsview but not the accordion.
After 4 hours of banging my head against the wall, I discovered that the DataSource field is VERY picky.
Here's my code:
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Branch");
dt.Columns.Add("Officer");
dt.Columns.Add("CustAcct");
dt.Columns.Add("Grade");
dt.Columns.Add("Rate");
dt.Columns.Add("OrigBal");
dt.Columns.Add("BookBal");
dt.Columns.Add("Available");
dt.Columns.Add("Effective");
dt.Columns.Add("Maturity");
dt.Columns.Add("Collateral");
dt.Columns.Add("LoanSource");
dt.Columns.Add("RBCCode");
dt.Rows.Add(new object[] { "James Bond, LLC", 120, "Garrison Neely", "123 3428749020", 35, "6.000", "$24,590", "$13,432",
"$12,659", "12/13/21", "1/30/27", 55, "ILS", "R"});
ds.Tables.Add(dt);
accReportData.DataSourceID = null;
accReportData.DataSource = ds.Tables[0].DefaultView;
accReportData.DataBind();
Turns out that the accordion only likes being bound to a dataset table's defaultview. I tried binding to just a DataTable (dt) and it failed. Even dt.DefaultView failed. Once I added it to a DataSet, it binds like a champ. Very annoying, with lost of wasted time. I know you've probably long-since forgotten this, but I wanted to make it available to future searchers. Accordion.DataSource must be bound to a DataSet.Table.DefaultView to work.
Make sure you specify a type for the columns in the table2.Columns.Add(...)
Also, as seen in the answer below:
https://stackoverflow.com/a/6108163/637903
You can bind the Accordion Control to a DataTableReader constructed from the original DataTable
accReportData.DataSource = new System.Data.DataTableReader(ds.Tables[0]);
accReportData.DataBind();

Categories

Resources