Monday, March 12, 2012

How to copy one datatable to another

Hi

I've got a typed Dataset class, myDatasetclass, which I generate an instance of (myDataset is the instance) and then store data locally inside the tables of this dataset instance.

Instead of "Filling" say, myDataset.tblUsers with a dataadapter directly however, my app sends this table to a windows service, which contacts a backend database, gets the data, and returns the 'myDataset.tblUsers', containing data, to my app.

Problem is, I need to be able to say something like:

Code Snippet

myDatasetclass myDataset = new myDatasetclass();

myDataset.tblUsers = myService.GetDatafromdbase(myDataset.tblUsers);

(this last part 'myDataset.tblUsers' is the table being sent to the service)

But it says myDataset.tblUsers (the first part above before the '=', is read-only, and can't be passed the new table with data which was returned from myService.

However, if I do this it works fine:

Code Snippet

Datasetclass.tblUsers mytblUsers = new Datasetclasss.tblUsers();

mytblUsers = myService.GetDatafromdbase(mytblUsers);

Only then, I'm filling a table by itself, instead of a table within the Dataset with all the relationships already established (because it's part of a class which establishes these relationships.)

It is becuase that DataTable can't be serialized and send as a result of WebService. Use Dataset for that, and you will get the table from dataset like this:

tblUsers = myService.GetDatafromdbase().Tables[0]; //if GetDatafromdbase returns a dataset that contain datatable tblUsers.

One more thing is that when you returning data, for this case table, better is to call it asynchronously, because every method has asinchronous method and event when that request is completed, it will be like this:

myService.GetDatafromdbaseCompleted += new GetDatafromdbaseCompletedEventHandler(OnUsersData);
myService.GetDatafromdbaseAsync();

for this you will create handler named OnUsersData:

private void OnUsersData(object sender, GetDatafromdbaseCompletedEventArgs e)
{
if (e.Result != null)
{
tblUsers = e.Result.Tables[0];
//do some other stuff if necessary, fill some grid, raise some other event, or any other action.
}
}


Thanks

Where you have:

Code Snippet

tblUsers = myService.GetDatafromdbase().Tables[0]

Do you mean:

Code Snippet

myDataset.tblUsers = myService.GetDatafromdbase().Tables[0]

Because tblUsers is partof the myDataset Dataset, and having this and = returns a 'read-only' error.


The myDataSet.tblUsers property is ReadOnly and can't be assigned to a new DataTable.

Instead you could try Merge:

myDataset.tblUsers.Merge(myService.GetDatafromdbase().Tables[0])

this will bring in all rows from the datatable.


How come I can still 'Fill' the table using an adapter if it is read-only?

eg:

adap.fill(myDataset.tblUsers);


What I did is auto-generated a typed dataset from my database, which also created a C# class file with all the tables and properties and relationships, whcih I intended to just create an instance of and write data to, but instead of using Fill, I'd use the

Code Snippet

myDataset.tblUsers = myService.GetDatafromdbase(myDataset.tblUsers);

Where the section in brackets is the table being sent to the service empty to be returned containing data.

Would it be best then to just 'rebuilt' all of this dataset in code (thats a lot of code for 50+ tables and relationships), and redefine all the relationships in code, seeing as I can't make an instance of the class mentioned above to write to?

Eg:

Code Snippet

myDataset newdataset = new myDataset();

myDataset.tblUsers newtblUsers = new myDataset.tblUsers();

myDataset.tblUsers newtblUsers = new myDataset.tblUsers();

...etc...

then put the tables in the dataset and define all the relationships?

Seems strange I can't just create an instance of my entire dataset class and then write table data into it with:

myDataset.tblUsers = myService.GetDatafromdbase(myDataset.tblUsers);

when using an adapter I could fill the myDataset.tblUsers table with data regardless of it being read-only.

If i create an instance of the table, but not the table within the dataset, the above works too, but then its a table by itself without relationships.

Labels: , , , , , , , , , , , , ,

How to copy Modified Records In a DataSet to another Dataset??

I have created a dataset from database "DB1" table "T_DB1". I Loop throw the Dataset and make changes/modification tosome of the records. After that I try to update the Dataset.
Lets say the update fails because database is down. I would like to create a backup of the modified data in a different database so I can load it manually latter on in the real database.
I am currently going throw every row of the dataset and finding what has been modified and the inserting that record into the backup database.

... BUT Is there any better way of doing this?This forum is falling appart. Its not like it used to be.
There is a way to do this.

You simply have to dynamically change your SQL statement and connection.

Eg. If your using a SqlDataAdapter, just change the update command associated with it and set it's connection property to the new database. All rows that have been updated will call this function which will update your backup database... I would look something like this:

Try
'Update database (main database)

Catch ex as Exception

'Check exception, if database is down then...
newConnectionString = new sqlConnection(".....")
mySqlDataAdapter.UpdateCommand = new sqlcommand(newConnectionString)
UpdateCommand.commandtext = ".............."

'Update backup database

End Try


Thats right. Thanks

Labels: , , , , , , , , , , , , , ,

how to copy dataset?

Hi all,

I have 2 datasets, how to copy all tables and data from dataset1 to dataset2?

I m using:

Rows.Add(Rows[ n ].ItemArray);

but i found it's too slow..

is there any better solution? thanks

Hi there,

I believe that the Dataset class has a Copy() function which you can use. It returns a new Dataset and apparently it copies all the tables and data.

Here's a link to the relevant portion of MSDN:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatasetclasscopytopic.asp

No MSDN2 I'm afraid, it seems to be dying on me at the moment.

Hope that helps a bit, but sorry if it doesn't

Labels: , , , , , , , , ,

How to convert time format

Hi all,

I had query some time information from the database and use a dataset to bind to a GridView.

But unfortunately, the time that display on the GridView is not my desired choice.

It was display as "3/1/2007 10:06:27 PM".

Does anyone know how to convert it as "3/1/2007 22:06:27"?

Part of my code is as follow

pgDataAdapter.Fill(ds,

"Start Time");

Thanks

Hi bslim67,

You can use the DataFormatString property of the GridView column to format the datetime value.

Hope this helps.


Hi,

Hi,

I had tried this.

<asp:BoundFieldDataField="starttime"dataformatstring="{0:dd/MMM/yy}"

HeaderText

="Start Time"ReadOnly="True"SortExpression="starttime"/>

But when I run the program during runtime, it seems that it did not take effect.

It still show me the date and time though my dataformat is only on date.

Please help.

Thanks


Dear , friend:

You should set HtmlEncode=false in the markup of:BoundField

I hope the above information will be helpful. If you have any issues or concerns, please let me know. It's my pleasure to be of assistance


Hi,

Thanks for your info. It's really a great help for me.

Labels: , , , , , , , , , , ,

how to convert sqldatasource to other type like dataview, dataset or datareader

Hi all,

i have got many problems with sqldatasource and dataview

--------------------------------
string ConnectionString = "Server=server;Integrated
Security=True;Database=contest;Persist Security Info=True";

string QueryString = "SELECT * FROM [members]";

System.Web.UI.WebControls.SqlDataSource SqlDataSource = new System.Web.UI.WebControls.SqlDataSource();

SqlDataSource.ConnectionString = ConnectionString;
SqlDataSource.SelectCommand = QueryString;
SqlDataSource.DataSourceMode = System.Web.UI.WebControls.SqlDataSourceMode.DataSet;

DataView dv = new DataView();

dv = (DataView)SqlDataSource;
--------------------------------

CS0030: Cannot convert type 'System.Web.UI.WebControls.SqlDataSource' to 'System.Data.DataView'

--------------------------------

i got similar problems if i use DataSet and DataReader.
SqlDataSource.DataSourceMode = System.Web.UI.WebControls.SqlDataSourceMode.DataSet;
SqlDataSource.DataSourceMode = System.Web.UI.WebControls.SqlDataSourceMode.DataReader;

--------------------------------

thx a lot.To return the DataSet from the SqlDataSource you have to use the SqlDataSource Select method. The Select method will return a DataView if the DataSourceMode of the SqlDataSource is set to System.Web.UI.WebControls.SqlDataSourceMode.DataSet.

If you set the mode to System.Web.UI.WebControls.SqlDataSourceMode.DataReader. A DataReader will be returned.
thx,
but, i dont know how to use sqldatasource as dataview after set it to dataset.
u have an example ?
thx
What is your purpose with the code? Do you only want to access a data source and get a Dataset back? If so I should recommend you to use SqlDataAdaptar:


DataSet ds = new DataSet();

using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", myConnectionString))
{
adapter.Fill(ds);
}

If you want to use SqlDataSource for some reason, here is an example:


string ConnectionString = "Server=localhost;Integrated Security=True;Database=Northwind;User=****;password=****;";
string QueryString = "SELECT * FROM [Employees]";
System.Web.UI.WebControls.SqlDataSource SqlDataSource = new System.Web.UI.WebControls.SqlDataSource();
SqlDataSource.ConnectionString = ConnectionString;
SqlDataSource.SelectCommand = QueryString;

DataSourceSelectArguments arg = new DataSourceSelectArguments();
System.Data.DataView dv = (System.Data.DataView)SqlDataSource.Select(arg);


okay thanks, now continuing on with system.data.dataview dv = ..., how do you retrieve a value, can you finish the code for us?
Many thanks,
Asaf

Here is the thing

DataView dv ;

dv = (DataView)DsOpenOrders.Select(DataSourceSelectArguments.Empty);

dv.Sort = SortField;

return dv;

DsOpenOrders is the SqlDataSource.

THis will help you I guess.

Thanks
Suda

Labels: , , , , , , , , ,

How to convert dataset to xml string with embedded schema

I have been trying to find a way to get an xml string with embedded schema from a dataset.

I know that you can use the .getxml and .getschema functions on the dataset but I do not see an easy way of combining those two results into one valid xml string.

I can't save anything to disk, everything has to happen in memory. I thought of using the .writexml method but you cannot use .writexml and pass a string...

Thank you for any thoughts you might have to solve this problem I am having.

Robertmaybe u can use the XmlSerializer object?

Labels: , , , , , , , , ,

How to convert Class object into DataSet?

Lets say, I have a following XSD utility generated class as follows:

[XmlRoot(Namespace="http://example.com/2007/ex1")]
public class Example {
public Example () {}
public string Name;
public int Power;
}

I have to pull data from several tables(MS Access2003) and store it in a DataSet.

Now, Is it possible to use it like:

Example example = new Example();
example.Power = 42;
example.Name = "Kibo";
DataSet myDataSet = new DataSet();
myDataSet = example;

or

myDataSet.Add(example);

Somehow, to add the example object tree in myDataSet, and pull values from tables directly into myDataSet.

This will help me in doing following things:

1. I'd not need to change my existing XSD generated class structure into DataSet.

2. Pull data directly into the DataSet, using explicit queries

3. Generate the Xml file directly.

Any help/idea/pointer/etc would help Alot.

Thanks.

The sample code you have given shouldn't work cause a DataSet can't load data from an custom entity object.

Check this site for more details:

http://msdn2.microsoft.com/en-us/library/ekw4dh3f(VS.80).aspx

http://msdn2.microsoft.com/en-us/library/ekw4dh3f(VS.80).aspx

Labels: , , , , , , , , , , , , , , ,

How to convert a untyped DataSet object to an strongly typed DataS

Hi!
I have to convert a untyped DataSet object to an strongly typed DataSet
object.
The method DataSet.Merge seen to be a good opportunity to convert the
DataSet. But I am not successfull with this method. Even when I rename the
property DataSetName and Table[0].TableName to exactly the right names.
What could be wrong? Do you have an idea or even better a little sample?
Thank for yout help!
GerdyGerda,
I don't know if this is a to simple sample.
http://www.windowsformsdatagridhelp.com/default.aspx?ID=edb1409d-5394-468f-a63f-de3a5d92b14a
I hope this helps,
Cor
Hi Cor!
Thanks for that link!
But it it's unsuggestive of showing how to convert a untyped DataSet object
into a strongly typed dataset.
It just shows how to merge a untyped DataSet with an untyped DataSet! How to
do this is already clear to me.
Perhaps I do not see the hint behind this sample! But this little sample is
not the support I am looking for :-(
Can you or someone else offer some more auxiliary references or relevant
samples showing how to convert a untyped DataSet into a strongly typed DataSet
Gerda
"Cor Ligthert [MVP]" wrote:
> Gerda,
> I don't know if this is a to simple sample.
> http://www.windowsformsdatagridhelp.com/default.aspx?ID=edb1409d-5394-468f-a63f-de3a5d92b14a
> I hope this helps,
> Cor
>
>
Gerda,
A strongly typed dataset inherits from a non strongly typed dataset. Merging
those two means that they have to be in fact almost identical in their
serialized version. (You cannot merge columns which don't exist in the
receiving table, than there will be created two tables).
If I would explain more, please reply.
Cor
Hi!
I guess I was very dizzy yesterday when I tried to convert a untyped DataSet
into a strongly typed DataSet!
This morning I found out that just a simple Merge ist the solution I am
looking for!
MyStronglyTypedDataSet stDs = new MyStronglyTypedDataSet();
DataSet untypedDs = new DataSet();
stDs.Merge(untypedDs);
This is all! This is the solution!
Gerda
"Gerda" wrote:
> Hi Cor!
> Thanks for that link!
> But it it's unsuggestive of showing how to convert a untyped DataSet object
> into a strongly typed dataset.
> It just shows how to merge a untyped DataSet with an untyped DataSet! How to
> do this is already clear to me.
> Perhaps I do not see the hint behind this sample! But this little sample is
> not the support I am looking for :-(
> Can you or someone else offer some more auxiliary references or relevant
> samples showing how to convert a untyped DataSet into a strongly typed DataSet
> Gerda
> "Cor Ligthert [MVP]" wrote:
> > Gerda,
> >
> > I don't know if this is a to simple sample.
> >
> > http://www.windowsformsdatagridhelp.com/default.aspx?ID=edb1409d-5394-468f-a63f-de3a5d92b14a
> >
> > I hope this helps,
> >
> > Cor
> >
> >
> >

Labels: , , , , , , , , , , ,

how to convert a row in gridview to my business class DialUpRow generated by dataSet desig

I have GridView with: objectdatasource="objectdatasource1"

Objectdatasource1 is linked to my BLL (business layer with a dataset designer genrating: DialUpRow as an item of my datatable: DialupUpDataTable

I want to convert the selected row to my class: DialUpRow

I get the selected row using: myGRidView.SelectedIndex

But I don t know how to convert the grid row to my DialUpRow in order to get intellisence of my row properies (calss properties in code behind)

DataItem property of the GridViewRow would give the dataitem bound to the GridView. Below is a sample code. In the code, I haven't done any error checking, please ensure you do in your code.

Dim row as GridViewRow = GridView1.Rows(GridView1.SelectedIndex)if row isnot nothing thenDim drow as DialUpRow =CType(row.DataItem, DialUpRow)endif

Labels: , , , , , , , , , , , , , , , , ,