Solved

Compare DataTables

Posted on 2010-11-15
14
826 Views
Last Modified: 2012-05-10
I am getting data from a database and putting it in a DataTable.  I then bind the datatable to a gridview.  I also set the datatable to another datatable named _datatable.  

I want to compare the datatable in the gridvew and _datatable to see if the data changed.  What is the easiest way to do this?

How do you extract the datasource of a gridview to a dataset?
0
Comment
Question by:CipherIS
  • 7
  • 6
14 Comments
 
LVL 6

Expert Comment

by:ajb2222
ID: 34136296
Why,

a datatable keeps track of changes.

The rowstate property of each datarow lets you know if there where changes to the datarow

you can look at the original data in a datarows column like this dtr.Rows[x]["columname",DataRowVersion.Original]
0
 
LVL 1

Author Comment

by:CipherIS
ID: 34136363
how do i set dtr = gridview.datasource?
0
 
LVL 6

Expert Comment

by:ajb2222
ID: 34136466
dtr is your original datatable

but you can also use

DataTable dtr = (DataTable)GridView1.DataSource;

where Gridview1 is the name of your GridView
0
 
LVL 9

Expert Comment

by:s_chilkury
ID: 34136632
///first convert gridview data to DataTable

then

////Code to Compare 2 DataTables and return a 3rd DataTable with difference

public DataTable CompareDataTables(DataTable first, DataTable second)
{
first.TableName = "FirstTable";
second.TableName = "SecondTable";

//Create Empty Table
DataTable table = new DataTable("Difference");

try
{
//Must use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

//Get Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

for (int j = 0; j < firstcolumns.Length; j++)
{
firstcolumns[j] = ds.Tables[0].Columns[j];
}

DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];

for (int j = 0; j < secondcolumns.Length; j++)
{
secondcolumns[j] = ds.Tables[1].Columns[j];
}

//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

ds.Relations.Add(r);

//Create columns for return table
for (int j = 0; j < first.Columns.Count; j++)
{
table.Columns.Add(first.Columns[j].ColumnName, first.Columns[j].DataType);
}

//If First Row not in Second, Add to return table.
table.BeginLoadData();

foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}

table.EndLoadData();

}
}
catch (Exception ex)
{
throw ex;
}

return table;
}


0
 
LVL 1

Author Comment

by:CipherIS
ID: 34136666
i'm having issues converting the gridview to datatable.

When I set the gridvdiew datasource to a datatable I get a null (see pic below)
datatable.jpg
0
 
LVL 1

Author Comment

by:CipherIS
ID: 34136876
how do i set viewstate to the gridview?
0
 
LVL 6

Expert Comment

by:ajb2222
ID: 34136926
Where do you originaly set the gvNotifications.Datasource?

You should have a line somewhere that looks something like this

dim dt as datatable;
// fill datatable here
gvNotifications.Datasource = dt;

If you set the datasource equal to some other type like a dataset,  you can only cast it back to that datatype, otherwise you get null.

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:CipherIS
ID: 34136985
DataTable dt = Notification.GetNotifications();  //Returns a DataTable
this.gvNotification.DataSource = dt;
0
 
LVL 1

Author Comment

by:CipherIS
ID: 34136995
DataTable dt = Notification.GetNotifications();  //Returns a DataTable
this.gvNotification.DataSource = dt;
this.gvNotification.DataBind();
0
 
LVL 6

Expert Comment

by:ajb2222
ID: 34137721
The databind()  tells me this is a web page.  Now I know Why you are trying to get the datatable back from the gridview.

What you need to do is store the datatable in a session variable like this

Session["MyData"] = dt;

and to get it back

dt = (DataTable)Session["MyData"];
0
 
LVL 1

Author Comment

by:CipherIS
ID: 34137781
This does not resolve my problem.  I can store the datatable but I need to get the changes from the gridview.  the gridview is not bound to the database.  data in the gridview is set by a datatable.  

Once the datatable is passed to the gridview i need to know what data changed.
0
 
LVL 6

Accepted Solution

by:
ajb2222 earned 500 total points
ID: 34138155
Since this is a web application,  you want to use the gridview events.

the RowUpdating event will allow you to check the data being updated and cancel the update if you need to.

this example will cancel the update if the first column has beeen changed to zero

       protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            DataTable dt = (DataTable)Session["MyData"];
            for(int x = 0; x < dt.Columns.Count; dt++)
            if (e.NewValues[0] != e.OldValues[0])
            {
                if (e.NewValues[0] = 0)

                    e.Cancel = true;

            }

        }

Open in new window


0
 
LVL 6

Expert Comment

by:ajb2222
ID: 34138204
Since you are not using an SQLDatasource the grid will not make the actual changes to your datatable.  

I would perform these in the RowUpdated event of the gridview wich fires after the row of the gridview has been updated.  It will not fire if the update has been canceled in RowUpdating.
0
 
LVL 1

Author Comment

by:CipherIS
ID: 34139502
i resolved the issue.  will award points for effort.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Parsing a CSV file is a task that we are confronted with regularly, and although there are a vast number of means to do this, as a newbie, the field can be confusing and the tools can seem complex. A simple solution to parsing a customized CSV fi…
This is used to tweak the memory usage for your computer, it is used for servers more so than workstations but just be careful editing registry settings as it may cause irreversible results. I hold no responsibility for anything you do to the regist…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now