getting value from datatable - asp.net

Can anyone please tell me how to get value from datatable? I've only got one row and one column in the datatable and I need to get the value of the column to do calculations.
here's my script
<SCRIPT Language="VB" Runat="server">
Sub Page_Load(Source as object, e as EventArgs) handles me.load
Dim connectionstring As String = "DRIVER={MySQL ODBC 5.2 Unicode Driver}; SERVER=localhost; DATABASE=mydb; UID=andrew; PASSWORD=kh12345; OPTION=3"
Dim connectme As OdbcConnection = New OdbcConnection(connectionstring)
Dim sqlquery As String = "SELECT f_name, f_price from tbl_picture WHERE f_ID = 1"
Dim ODBCdataadapter As OdbcDataAdapter = New OdbcDataAdapter(sqlquery, connectme)
Dim ODBCdataset As DataSet = New DataSet()
ODBCdataadapter.Fill(ODBCdataset)
DataTable.DataSource = ODBCdataset
DataTable1.DataSource = ODBCdataset
Datatable.DataBind()
Datatable1.DataBind()
End Sub
</SCRIPT >
<ASP:Datagrid ID="Datatable1" Runat="server" AutoGenerateColumns="False"BorderStyle="None" GridLines="None">
<Columns>
<asp:BoundColumn
DataField="f_price"
ReadOnly="True"/>
</columns>
</asp:DataGrid>
and here's the calculation part
Private Sub CalculatePayment()
Dim c_loan_amount, c_Payment
Dim amount As String = Datatable1.Select("f_price")
c_loan_amount = amount - (amount * Down.Text * 0.01)
c_Payment = ((c_loan_amount * (Interest.Text * 0.01) * Year.Text) + c_loan_amount) / (Year.Text * 12)
Payment.Text = "RM " & Format(c_Payment, "#,##0.00")
End Sub
It should be the Dim amount as string part right? I'm kinda new, thanks in advance.

You need to define the row and item.
Try
Dim amount As String = Datatable1.tables(0).Rows(0).Item(1)
Actually you should rename datatable1 to dataset1 since a datatable is a possible member of a dataset. Its just to minimize confusion of what is what.
The Rows tells which row of the datatable. The item tells which index.
0 = f_name
1 = f_amount

Related

Asp.net repeater databind on postback

SOLUTION FOR FUTURE REFERENCE
Problem was the "tecnico" variable that became 0 at every postback, also to avoid any problem I get rid of global variables data1 and data2 and moved them inside the Bindrepeater routine, like this:
Dim data1, data2 As DateTime
If Len(ViewState("dataDa")) = 0 Then
data1 = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
data2 = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
ViewState("dataDa") = data1
ViewState("dataA") = data2
Else
data1 = Date.ParseExact(ViewState("dataDa"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(ViewState("dataA"), "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
End If
ORIGINAL QUESTION
I'm having trouble with databind of a repeater on page load. I would make a sort of weekly calendar, so the repeater should show dates and for every day a nested repeater should show appointments. I made a simple week selector with a Previous/Next button to move through weeks. It work fine on first page load, but it shows nothing when I use the buttons to change active week.
I know the problem is the postback for sure, but I can't get around this... any help?
html:
<div id="divCalendario" class="panel" runat="Server">
<div id="divCalendarNavigator" style="display: block;" runat="server">
<div>
<%--<asp:Calendar runat="server" ID="calendar" SelectionMode="DayWeek" TitleStyle-ForeColor="#1f7872" TitleStyle-Font-Bold="true" PrevMonthText="<i class=icon-foo></i>" NextMonthText="<i class=icon-foo></i>" NextPrevStyle-Font-Names="FontAwesome" SelectWeekText="<i class=icon-foo></i>" SelectorStyle-Font-Names="FontAwesome" WeekendDayStyle-BackColor="LightGray" SelectedDayStyle-BackColor="#f3ef98" SelectedDayStyle-ForeColor="Black" SelectedDayStyle-Font-Bold="true" OnSelectionChanged="calendar_SelectionChanged"></asp:Calendar>--%>
<asp:LinkButton runat="server" ID="lnkPrevWeek" OnClick="lnkPrevWeek_Click"><i class="fa fa-arrow-circle-o-left" aria-hidden="true"></i></asp:LinkButton>
<asp:Literal ID="litData" runat="server"></asp:Literal>
<asp:LinkButton runat="server" ID="lnkNextWeek" OnClick="lnkNextWeek_Click"><i class="fa fa-arrow-circle-o-right" aria-hidden="true"></i></asp:LinkButton>
<asp:HiddenField runat="server" ID="hdnDa" /><asp:HiddenField runat="server" ID="hdnA" /><asp:HiddenField runat="server" ID="hdnSpostamento"/>
<asp:DropDownList ID="ddlTecnicoCal" runat="server" AppendDataBoundItems="true" CssClass="tendina" placeholder="Tecnico" AutoPostBack="true">
<%--<asp:ListItem Value="-1">Tutti</asp:ListItem>--%>
</asp:DropDownList>
</div>
</div>
<asp:Repeater ID="rptParent" runat="server">
<ItemTemplate>
<p style="margin-left: 10px"><b>
<asp:Label ID="lblDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "data", "{0:dd/MM/yyyy}")%>'></asp:Label></b></p>
<asp:Repeater ID="rptAppuntamenti" runat="server">
<ItemTemplate>
<%# Eval("id")%></td>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
</div>
CODE:
Imports System.Data.SqlClient
Imports System.Globalization
Public Class Calendario
Inherits System.Web.UI.Page
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Public Function GetDayFromWeek(week As DateTime, day As DayOfWeek) As DateTime
Dim startDay As DayOfWeek = System.Threading.Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek
' get the beginning of the week
Dim diff As Integer = CInt(week.DayOfWeek) - CInt(startDay)
Dim beginingOfWeek As DateTime = week.AddDays(diff * -1)
' get the day we are looking for
diff = CInt(day) - CInt(startDay)
If diff < 0 Then
diff = 7 - CInt(startDay)
End If
Return beginingOfWeek.AddDays(diff)
End Function
Public Function datasql(ByVal dataini As Date) As String
Return dataini.Year & "-" & dataini.Month & "-" & dataini.Day
End Function
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
caricaTecnici()
Dim monday = GetDayFromWeek(Date.Today, DayOfWeek.Monday)
Dim sunday = GetDayFromWeek(Date.Today, DayOfWeek.Sunday)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
Dim dbVulcano As New dbVulcanoEntities
data1 = Date.ParseExact(monday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(sunday, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
tecnico = Session("idUtente")
utente = dbVulcano.Utenti.Where(Function(u) u.IDUtente = tecnico).Single
End If
BindRepeater()
End Sub
Private Sub BindRepeater()
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select distinct(statoRic.DataAss) as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null and statoric.DataAss between #data1 and #data2 And RFTecnico=#tecnico
group by statoRic.DataAss order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data1", data1)
cmd.Parameters.AddWithValue("#data2", data2)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
rptParent.DataSource = dt
rptParent.DataBind()
End Using
End Using
End Using
End Sub
Private Sub rptParent_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rptParent.ItemDataBound
If (e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem) Then
Dim childRepeater As Repeater = e.Item.FindControl("rptAppuntamenti")
Dim lblDate As Label = e.Item.FindControl("lblDate")
'Dim lblTecnico As Label = e.Item.FindControl("lblTecnico")
Dim data As DateTime = Date.ParseExact(lblDate.Text, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
'lblTecnico.Text = utente.NomeExt
Dim constr As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Dim query As String = "Select statoric.id, (case when clienti.IDCliente = 796 then richieste.descr else clienti.RagSociale end) as RagSociale, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraDalle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraDalle % 100)),'00:00') as eventstart, CAST(statoRic.DataAss AS DATE) + ISNULL(CONVERT(datetime, CONVERT(varchar(10), statoRic.OraAlle / 100)+ ':' + CONVERT(varchar(10), statoRic.OraAlle % 100)),'00:30') as eventend, Utenti.Nome as tecnico, statoRic.DataAss as data
From StatoRic
INNER Join
(Richieste INNER JOIN Clienti
On clienti.IDCliente=Richieste.RFCliente)
On StatoRic.RFRic=Richieste.IDRic
join Utenti
On utenti.IDUtente=StatoRic.RFTecnico
WHERE(RFStato = 11 or RFStato = 12 Or rfstato = 13 Or rfstato = 41) And Attuale=1 and StatoRic.DataAss is not null And RFTecnico=#tecnico and statoric.DataAss = #data
order by statoRic.DataAss asc"
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand(query, con)
cmd.Parameters.AddWithValue("#data", data)
cmd.Parameters.AddWithValue("#tecnico", tecnico)
Using sda As New SqlDataAdapter(cmd)
Dim dt As New DataTable()
sda.Fill(dt)
childRepeater.DataSource = dt
childRepeater.DataBind()
End Using
End Using
End Using
End If
End Sub
Sub caricaTecnici()
Dim Query As String = "SELECT nome,idutente FROM Utenti WHERE attivo=1"
Dim cmd As New SqlCommand(query)
ddlTecnicoCal.DataSource = GetData(cmd)
ddlTecnicoCal.DataTextField = "nome"
ddlTecnicoCal.DataValueField = "idutente"
ddlTecnicoCal.DataBind()
ddlTecnicoCal.SelectedIndex = ddlTecnicoCal.Items.IndexOf(ddlTecnicoCal.Items.FindByValue(Session("idUtente")))
End Sub
Private Function GetData(cmd As SqlCommand) As DataTable
Dim strConnString As String = ConfigurationManager.ConnectionStrings("dbVulcanoConnectionString").ConnectionString
Using con As New SqlConnection(strConnString)
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function
Protected Sub lnkPrevWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(-7)
Dim sunday = data2.AddDays(-7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
Protected Sub lnkNextWeek_Click(sender As Object, e As EventArgs)
data1 = Date.ParseExact(hdnDa.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
data2 = Date.ParseExact(hdnA.Value, "dd/MM/yyyy", CultureInfo.CreateSpecificCulture("en-US")).Date
Dim monday = data1.AddDays(7)
Dim sunday = data2.AddDays(7)
hdnDa.Value = monday
hdnA.Value = sunday
litData.Text = monday & " " & sunday
BindRepeater()
End Sub
End Class
Thanks!
I think your problem could be your global variables not preserving their new value after postback:
Dim data1, data2 As DateTime
Dim tecnico As Integer
Dim utente As Utenti
Try to store the values inside Session variables or Viewstate instead.
For example:
Session("tecnico") = x
ViewState("utente") = y
I've had this issue in the past.
The global variable doesn't keep its value

gridview PageIndexChanging issue

I am trying to to loop through a dataset's value through the rows in a gridview and color in the text if that row matches.
The code below works however whenever I change the page through the PageIndexChanging and this function is ran again, the coloring doesn't work anymore. It still loops through the gridview if there is a match but the effects are not shown.
--variable initialization class instantiation--
--code to connect to db here--
mySQLCommand.CommandText = "SELECT ..."
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDataset)
Me.MainPageGridView.DataSource = myDataset
Me.MainPageGridView.DataBind()
mySQLCommand.CommandText = "SELECT ... The ID's to be matched"
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDatasetNew)
Me.MainPageGridView.DataSource = myDatasetNew
For Each dataRow In myDataset.Tables(0).Rows
thisID = dataRow("ID").ToString
For Each gvRow In Me.MainPageGridView.Rows
If gvRow.Cells(2).Text = thisID Then
For column = 0 To 14 Step 1
gvRow.Cells(column).ForeColor = Drawing.Color.RosyBrown
Next
Exit For
End If
Next
Next
Why don't you use MainPageGridView_RowDataBound event to match the id? I have re-factored your original code to something like below, please check and let me know if it works:
'In DataBind or some other method
'Load(myDataSet)
mySQLCommand.CommandText = "SELECT ..."
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDataset)
'Load myDatasetNew and bind it to grid
mySQLCommand.CommandText = "SELECT ... The ID's to be matched"
mySQLAdapter = New SqlDataAdapter(mySQLCommand)
mySQLAdapter.Fill(myDatasetNew)
Me.MainPageGridView.DataSource = myDatasetNew
Me.MainPageGridView.DataBind()
and perform id matching in
Protected Sub MainPageGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles MainPageGridView.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim id As String = DataBinder.Eval(e.Row.DataItem, "ID") 'The name of ID column in "myDatasetNew"
Dim dv As System.Data.DataView = myDataset.Tables(0).DefaultView
dv.RowFilter = "ID = " & id
If dv.Count > 0 Then 'id matches
'Change foreclor of entire row
e.Row.ForeColor = Drawing.Color.RosyBrown
End If
End If
End Sub
You really need to do your data comparison in the GridView.RowDataBound event.

vb.net - Inserting number of files named XX into a string

Have the following code which creates a table of all the images in a folder.
VB:
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
Dim dirInfo as New DirectoryInfo(Server.MapPath("/images"))
articleList.DataSource = dirInfo.GetFiles("*.jpg")
articleList.DataBind()
End If
End Sub
Body:
<asp:DataGrid runat="server" id="articleList" AutoGenerateColumns="False" ShowHeader="false">
<Columns>
<asp:BoundColumn DataField="Name" />
</Columns>
</asp:DataGrid>
The results look something like this:
aa_01.jpg
aa_02.jpg
aa_03.jpg
bb_01.jpg
bb_02.jpg
cc_01.jpg
cc_02.jpg
cc_03.jpg
cc_04.jpg
...
What I want to do now is group all these by the first two characters and get the total number for each and insert them into individual strings. So for the above example it would be something like:
Dim aa As String = 3
Dim bb As String = 2
Dim cc As String = 4
Any ideas how?
You can do this using Linq. Try this.
dim q = From p in articles _
Group By Name = p.Name.SubString(0,2) into g = group _
Select GroupName = Name, _
Count = g.Count()
Update (to give a bit of context as per comments)
Sub Page_Load(sender as Object, e as EventArgs)
If Not Page.IsPostBack then
Dim dirInfo as New DirectoryInfo(Server.MapPath("/images"))
Dim articles = dirInfo.GetFiles("*.jpg")
articleList.DataSource = articles
articleList.DataBind()
Dim groupings = From p in articles _
Group By Name = p.Name.SubString(0,2) into g = group _
Select GroupName = Name, _
Count = g.Count()
' do whatever you like with the groupings '
End If
End Sub
In C#, using LINQ:
groupedArticleList = (from a in articleList
group a by a.Name.Substring(0, 2) into g
select new
{
GroupName = g.Key,
ArticleCount = g.Count()
});
You can't really extract them into separate variables but you could use groupedArticleList as-is and loop through it or convert it to a Dictionary<string, int>.
Sorry I don't know the VB syntax but hopefully that will help.

compare the content of 2 gridviews in one aspx page

we need to compare the content of 2 identical gridviews and extract rows that differ in a third gridview, is this doable?
i tried a lot but faced no luck, please help me.
at our office we take daily backup of ASP.net application ms access backend
for the next few days we need to evaluate the changes made to records in the database tables
at the end of each day i want to compare 2 access databases first database is the backup of yesterday and second database is the backup of today
i thought of the following algorithm, please read carefully and tell me how to proceed to compare the datatables / gridviews
i need to display th rows / cells containing the differences / updates / deleted data
comparing two ms access backend databases of an asp.net web application
my team and myseld figured it out
Imports System.Data
Imports System.Data.OleDb
Partial Class MoKoTrack
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myDB = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|databaseName.mdb;Persist Security Info=True")
Session("CurrentDB") = myDB
myDB.open()
Dim mytables = myDB.GetOleDbSchemaTable(OleDbSchemaGuid.Primary_Keys, New Object() {})
Dim CurrentTable As String
For i = 1 To mytables.Rows.Count
CurrentTable = mytables.Rows(i - 1).Item(2).ToString
If CurrentTable.Contains("Backup") Then CompareTable(CurrentTable, mytables.Rows(i - 1).Item(3).ToString)
Next i
' Dim myGrid As New GridView
'myGrid.DataSource = mytables
'myGrid.DataBind()
'Me.Form.Controls.Add(myGrid)
'myDB.Close()
End Sub
Sub CompareTable(ByVal BackupTableName As String, ByVal myPrimKey As String)
Dim OriginalTable As New DataTable
Dim BackupTable As New DataTable
Dim ModificationsTable As New DataTable
Dim AddedTable As New DataTable
Dim DeletedTable As New DataTable
Dim myDB = Session("CurrentDB")
Dim FinalSQLString = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand = New OleDbCommand(FinalSQLString, myDB)
Dim myReader As IDataReader = myDBCommand.ExecuteReader()
BackupTable.Load(myReader)
Dim OriginalTableName = Left(BackupTableName, Len(BackupTableName) - 6)
Dim FinalSQLString2 = "SELECT * FROM [" + OriginalTableName + "]"
Dim myDBCommand2 = New OleDbCommand(FinalSQLString2, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader2 As IDataReader = myDBCommand2.ExecuteReader()
OriginalTable.Load(myReader2)
Dim myPrimColumn(0) As DataColumn
myPrimColumn(0) = OriginalTable.Columns(myPrimKey)
OriginalTable.PrimaryKey = myPrimColumn
Dim myPrimColumn2(0) As DataColumn
myPrimColumn2(0) = BackupTable.Columns(myPrimKey)
BackupTable.PrimaryKey = myPrimColumn2
AddedTable = OriginalTable.Clone
DeletedTable = OriginalTable.Clone
ModificationsTable = OriginalTable.Clone
ModificationsTable.PrimaryKey = Nothing
Dim CurrentVal As String
For i = 0 To OriginalTable.Rows.Count - 1
CurrentVal = OriginalTable.Rows(i).Item(myPrimKey).ToString
Dim foundRow As DataRow = BackupTable.Rows.Find(CurrentVal)
If foundRow IsNot Nothing Then
For t = 0 To OriginalTable.Columns.Count - 1
If Not foundRow.Item(t).ToString = OriginalTable.Rows(i).Item(t).ToString Then
ModificationsTable.ImportRow(OriginalTable.Rows(i))
'ModificationsTable.Rows(ModificationsTable.Rows.Count - 1).Item(t) = ModificationsTable.Rows(ModificationsTable.Rows.Count - 1).Item(t) & "Modified"
ModificationsTable.ImportRow(foundRow)
End If
Next
Else
AddedTable.ImportRow(OriginalTable.Rows(i))
End If
Next
For i = 0 To BackupTable.Rows.Count - 1
CurrentVal = BackupTable.Rows(i).Item(myPrimKey).ToString
Dim foundRow As DataRow = OriginalTable.Rows.Find(CurrentVal)
If foundRow Is Nothing Then
DeletedTable.ImportRow(OriginalTable.Rows(i))
End If
Next
If AddedTable.Rows.Count > 0 Then
Dim myLabel As New Label
myLabel.Text = "<br/> The following records were added to table " & OriginalTableName & "<br/> <br/>"
Me.form1.Controls.Add(myLabel)
Dim myGrid As New GridView
myGrid.DataSource = AddedTable
myGrid.DataBind()
Me.form1.Controls.Add(myGrid)
End If
If ModificationsTable.Rows.Count > 0 Then
Dim myLabel As New Label
myLabel.Text = "<br/> The following records were modified in table " & OriginalTableName & "<br/> <br/>"
Me.form1.Controls.Add(myLabel)
Dim myGrid As New GridView
myGrid.DataSource = ModificationsTable
myGrid.DataBind()
Me.form1.Controls.Add(myGrid)
End If
If DeletedTable.Rows.Count > 0 Then
Dim myLabel As New Label
myLabel.Text = "<br/> The following records were deleted from table " & OriginalTableName & "<br/> <br/>"
Me.form1.Controls.Add(myLabel)
Dim myGrid As New GridView
myGrid.DataSource = DeletedTable
myGrid.DataBind()
Me.form1.Controls.Add(myGrid)
End If
End Sub
End Class
I usually compare it using LINQ
This will give you a head start
var SearchResults1 = from u in YourDB.YourUserTable1
orderby u.YourColumn
select u;
GridView1.DataSource = SearchResults1;
GridView1.DataBind();
var SearchResults2 = from u in YourDB.YourUserTable2
orderby u.YourColumn
select u;
GridView2.DataSource = SearchResults2;
GridView2.DataBind();
var SearchResults3 = from u1 in SearchResults2
where !(from u2 in SearchResults1
select u2.YourTablePrimaryKey).Contains(u1.YourTablePrimaryKey)
orderby u1.YourColumn
select u1;
GridView3.DataSource = SearchResults3;
GridView3.DataBind();
You can further elaborate SearchResults 3 if you want like comparing whats in SearchResults1 but not in SearchResults2 and vice versa

comparing two ms access backend databases of an asp.net web application

at our office we take daily backup of ASP.net application ms access backend
for the next few days we need to evaluate the changes made to records in the database tables
at the end of each day i want to compare 2 access databases first database is the backup of yesterday and second database is the backup of today
i thought of the following algorithm, please read carefully and tell me how to proceed to compare the datatables / gridviews
i need to display th rows / cells containing the differences / updates / deleted data
Imports System.Data
Imports System.Data.OleDb
Partial Class MoKoTrack
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim myDB = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|database.mdb;Persist Security Info=True")
Session("CurrentDB") = myDB
myDB.open()
Dim mytables = myDB.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {})
Dim CurrentTable As String
Dim ee As Integer = mytables.Rows.Count
Dim OriginalTables(ee) As String
Dim BackupTables(ee) As String
Dim X As Integer = 0
For i = 1 To mytables.Rows.Count
CurrentTable = mytables.Rows(i - 1).Item(2).ToString
If mytables.Rows(i - 1).Item(3).ToString = "TABLE" Or mytables.Rows(i - 1).Item(3).ToString = "VIEW" Then
If CurrentTable.Contains("Backup") Then
BackupTables(X) = CurrentTable
Else
OriginalTables(X) = CurrentTable
End If
X = X + 1
End If
Next i
For i = 0 To BackupTables.Count - 1
If Not BackupTables(i) = "" Then
CompareTable(BackupTables(i))
End If
Next
myDB.Close()
End Sub
Sub CompareTable(ByVal BackupTableName As String)
Dim OriginalTable As New DataTable
Dim BackupTable As New DataTable
Dim ModificationsTable As New DataTable
Dim myDB = Session("CurrentDB")
Dim FinalSQLString = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand = New OleDbCommand(FinalSQLString, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader As IDataReader = myDBCommand.ExecuteReader()
'Dim myColumns = myReader.GetSchemaTable
'For I = 1 To myColumns.Rows.Count
' OriginalTable.Columns.Add(myColumns.Rows(I - 1).Item(0).ToString())
'Next I
BackupTable.Load(myReader)
Dim OriginalTableName = Left(BackupTableName, Len(BackupTableName) - 6)
Dim FinalSQLString2 = "SELECT * FROM [" + BackupTableName + "]"
Dim myDBCommand2 = New OleDbCommand(FinalSQLString, myDB)
'Generate a temporary reader to get the number of cases
Dim myReader2 As IDataReader = myDBCommand.ExecuteReader()
OriginalTable.Load(myReader2)
'Dim myGrid As New GridView
'myGrid.DataSource = OriginalTable
'myGrid.DataBind()
'Me.form1.Controls.Add(myGrid)
'Dim myGrid2 As New GridView
'myGrid2.DataSource = BackupTable
'myGrid2.DataBind()
'Me.form1.Controls.Add(myGrid2)
For i = 0 To OriginalTable.Rows.Count - 1
For t = 0 To OriginalTable.Columns.Count - 1
Next
Next
End Sub
End Class
i am using the following VBA code to rename backup database tables into "tablebackup"
Private Sub Command0_Click()
Dim tdf As TableDef
For Each tdf In CurrentDb.TableDefs
If Left(tdf.Name, 4) <> "MSys" Then
tdf.Name = tdf.Name & "backup"
End If
Next
End Sub
Can you add a ModifiedOn field for each table and extract the rows that have been modified since the last day. You can compare the modified ones (the ones that exist in the backup) and write out all new ones (the ones that don't).

Resources