4advanced 23 Junior Poster in Training

This example code explains maybe :=)

Dim _DT As DataTable = Nothing

    Private Sub Form2_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        _DT = New DataTable
        _DT.BeginLoadData()

        For i As Integer = 0 To 5
            Dim _Col As DataColumn = New DataColumn("", System.Type.GetType("System.String"))
            _DT.Columns.Add(_Col)
            _Col.Dispose()
            _Col = Nothing
        Next

        For i As Integer = 0 To 5
            Dim _Row As DataRow = _DT.NewRow
            _Row.Item(0) = String.Format("Test {0}", i.ToString)
            _DT.Rows.Add(_Row)
        Next
        _DT.EndLoadData()
        _DT.AcceptChanges() 
        Me.BindingSource1.DataSource = _DT

        Me.DataGridView1.DataSource = Me.BindingSource1

    End Sub

    Private Sub BindingSource1_CurrentItemChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles BindingSource1.CurrentItemChanged
        Dim tmpTable As DataTable = _DT.GetChanges(System.Data.DataRowState.Modified)
        Me.DataGridView2.DataSource = tmpTable
    End Sub

MSDN says....

When you call AcceptChanges on the DataSet, any DataRow objects still in edit-mode end their edits successfully. The RowState property of each DataRow also changes; Added and Modified rows become Unchanged, and Deleted rows are removed.

4advanced 23 Junior Poster in Training

Ossehaas,

Check the StreamingContext class for additional info.... I think it will help ya out....

According MSDN:

Imports System
Imports System.Text
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Security.Permissions


Class Program

    Shared Sub Main(ByVal args() As String) 
        Try
            SerializeAndDeserialize()
        Catch exc As System.Exception
            Console.WriteLine(exc.Message)
        Finally
            Console.WriteLine("Press <Enter> to exit....")
            Console.ReadLine()
        End Try

    End Sub 

    Shared Sub SerializeAndDeserialize() 
        Dim myObject As Object = DateTime.Now
        ' Create a StreamingContext that includes a
        ' a DateTime. 
        Dim sc As New StreamingContext(StreamingContextStates.CrossProcess, myObject)
        Dim bf As New BinaryFormatter(Nothing, sc)
        Dim ms As New MemoryStream(New Byte(2047) {})
        bf.Serialize(ms, New [MyClass]())
        ms.Seek(0, SeekOrigin.Begin)
        Dim f As [MyClass] = CType(bf.Deserialize(ms), [MyClass])
        Console.WriteLine(vbTab + " MinValue: {0} " + vbLf + vbTab + " MaxValue: {1}", f.MinValue, f.MaxValue)
        Console.WriteLine("StreamingContext.State: {0}", sc.State)

        Dim myDateTime As DateTime = CType(sc.Context, DateTime)
        Console.WriteLine("StreamingContext.Context: {0}", myDateTime.ToLongTimeString())

    End Sub 
End Class 

<Serializable(), SecurityPermission(SecurityAction.Demand, SerializationFormatter := True)>  _
Class [MyClass]
    Implements ISerializable
    Private minValue_value As Integer
    Private maxValue_value As Integer

    Public Sub New() 
        minValue_value = Integer.MinValue
        maxValue_value = Integer.MaxValue    
    End Sub     

    Public Property MinValue() As Integer 
        Get
            Return minValue_value
        End Get
        Set
            minValue_value = value
        End Set
    End Property 

    Public Property MaxValue() As Integer 
        Get
            Return maxValue_value
        End Get
        Set
            maxValue_value = value
        End Set
    End Property

    Sub GetObjectData(ByVal si As SerializationInfo, ByVal context As StreamingContext)  Implements ISerializable.GetObjectData
        si.AddValue("minValue", minValue_value)
        si.AddValue("maxValue", maxValue_value)

    End Sub   

    Protected Sub New(ByVal si As SerializationInfo, ByVal context As StreamingContext) 
        minValue_value = Fix(si.GetValue("minValue", GetType(Integer)))
        maxValue_value = Fix(si.GetValue("maxValue", GetType(Integer)))
    End Sub 
End Class
4advanced 23 Junior Poster in Training

Can you tell us what happens before we have to puzzle?

(think about getting your car back to the shop & ask the technician if he can tell you what's wrong with your car?)

4advanced 23 Junior Poster in Training

No sorry, it's time to find out yourself....
I coded an example and added comments to it, so you know what steps to take.

Now it's up to you.......

Jx_Man commented: Good +12
4advanced 23 Junior Poster in Training

Okay, here it is :

Private Sub cmdSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdSearch.Click

        'variabeles (objects and strings)
        Dim _root As String = String.Empty
        Dim _Con As OleDb.OleDbConnection = Nothing
        Dim _WhereClause As String = String.Empty
        Dim _Parameter As OleDbParameter = Nothing
        Dim _DataTable As DataTable = Nothing
        Dim _Com As OleDbCommand = Nothing
        Dim _DataAdapter As OleDbDataAdapter

        'fill string variabeles
        _root = "yourPathToDatabase\MyDataBase.mdb"
        _Con = New OleDb.OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};User Id=admin;Password=;", _root))

        'create objects
        _Com = New OleDbCommand
        _DataTable = New DataTable("Customers")
        _DataAdapter = New OleDbDataAdapter

        'check if the searchstring is numeric (if so, the search for an ID has been performed)
        If IsNumeric(txtSearch.Text) Then
            _WhereClause = "ID=@Parameter"
        Else
            _WhereClause = "LCASE(Customer_LastName)=@Parameter"
        End If

        Try
            'open the connection to the database
            _Con.Open()

            'fill the command with the selectquery and attach a parameter
            With _Com
                .CommandText = String.Format("SELECT * FROM Customers WHERE {0}", _WhereClause)
                .Parameters.AddWithValue("@Parameter", txtSearch.Text.ToLower)
                .Connection = _Con
            End With

            'attach command to dataadapter and fill the datatable
            _DataAdapter.SelectCommand = _Com
            _DataAdapter.Fill(_DataTable)

        Catch ex As Exception
            'inform the user something has happened
            MessageBox.Show(ex.Message)
        Finally

            'if the connection is open, close it
            If _Con.State = ConnectionState.Open Then _Con.Close()
            'dispose and remove objects
            _Con.Dispose()
            _Con = Nothing
            _Com.Dispose()
            _Com = Nothing
        End Try

        'attach the datatable to the datagridview
        Me.dgvCustomers.DataSource = _DataTable

        'dispose and remove objects
        _DataAdapter.Dispose()
        _DataAdapter = Nothing
        _DataTable.Dispose()
        _DataTable = Nothing

    End Sub
4advanced 23 Junior Poster in Training

Like Jx_Man says.... use that condition in your select statement. For example like this : SELECT * from UMP WHERE ID = yourID -> 'yourID' is the ID which you are looking for.

A better approach is : use parameterized queries so instead of yourID you can insert at that point @yourID and declare a parameter object, insert the correct value in it and attach the parameter to the commandobject! This way, it's sql-injection safe....

4advanced 23 Junior Poster in Training

At least you are pointing to the right directions at this moment. The questions you ask seem to me you are now in the right 'developer-mode' :=)

Professor can be right but it's up to you where to open the connection. In most cases, and esspecially for .Net, the connections are made when you want to query, update, insert or delete something from the database and close it when ready. Anyways, you still can open the connection whenever you want & close it whenever you want.

In the case of using Access as a backend database, you're out of many options. You got to remember that Access is a file-based database which means that if you query some tables, all the tables in the query are pulled over to the client and after that they are being queried (client side). With a lot of data, you can experience a lot of performance problems.

Pointing to your question: leave all database actions within the button_click, as ProfessorPC suggested. Take a look at this post http://www.daniweb.com/forums/thread172996.html and look for rapture's code examples on oledb connections etc....
Also ProfessorPC's example is a nice solution ;)

Regards,
Richard
The Netherlands

4advanced 23 Junior Poster in Training

You must have 2 parameters declared in your Stored Procedure, called @DR and @CR, both of the type Decimal.
While looping through your rows in your LoadCashBookDataSet.Tables(0) you have to execute the command based on the stored procedure & active connection. So, each time you have passed a row, you have to execute the command in order to update your databasetable.

This means you have to try something like this: (the code should be cleaned up & added with cleanup code for your unmanaged objects like the connection and command)

Private Sub ButtonReconsilation_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonReconsilation.Click

Dim connection As SqlConnection = database_connection()
Try
    connection.Open()
Catch ex as exception
   msgbox ex.message
End Try

Dim count as integer = 0
dim I As Integer = 0
Dim command As SqlCommand = nothing

Try

count = LoadCashBookDataSet.Tables(0).Rows.Count
While I < count
command= New SqlCommand("insertCashBook", connection)
command.CommandType = CommandType.StoredProcedure


If NZ(LoadCashBookDataSet.Tables(0).Rows(I)(4)) = 0 Then
command.Parameters.AddWithValue("@DR", NZ(LoadCashBookDataSet.Tables(0).Rows(I)(4)))
command.Parameters.AddWithValue("@CR", Convert.ToDecimal(LoadCashBookDataSet.Tables(0).Rows(I)(5)))

ElseIf NZ(LoadCashBookDataSet.Tables(0).Rows(I)(5)) = 0 Then
command.Parameters.AddWithValue("@CR", NZ(LoadCashBookDataSet.Tables(0).Rows(I)(4)))
command.Parameters.AddWithValue("@DR", Convert.ToDecimal(LoadCashBookDataSet.Tables(0).Rows(I)(4)))

Else
command.Parameters.AddWithValue("@DR", Convert.ToDecimal(LoadCashBookDataSet.Tables(0).Rows(I)(4)))
command.Parameters.AddWithValue("@CR", Convert.ToDecimal(LoadCashBookDataSet.Tables(0).Rows(I)(5)))
End If
command.ExecuteNonQuery() 
'I = I + 1
[b]I += 1[/b]
End While

'Receive Error while execute this statement 
Catch ex As Exception
MsgBox(Err.Description)
End Try

End Sub
4advanced 23 Junior Poster in Training

To help you a little more:

You also can add a ContextMenuStrip to your solution and respond on the rightclicking of a user into one of the columns in your datagrid.
For example, if the user rightclicks into a column a menuitem will be shown with "show all data". If clicked, that particular column will be autosized.

Add the variabele _ActiveColumn to the general declaration section.
Add a contextmenu to your solution with 1 item "Show all data"

Private _ActiveColumn As Integer = 0


    Private Sub DataGridView1_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
        _ActiveColumn = e.ColumnIndex

        If e.Button = Windows.Forms.MouseButtons.Right Then
            Me.ContextMenuStrip1.Show(Me.DataGridView1, New Point(e.X, e.Y))
        End If

    End Sub

    Private Sub ShowAllDataToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowAllDataToolStripMenuItem.Click
        For Each oCol As DataGridViewColumn In Me.DataGridView1.Columns
            If oCol.Index = _ActiveColumn Then
                oCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            Else
                oCol.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
            End If
        Next
    End Sub
4advanced 23 Junior Poster in Training

Something like this?
It will expand the last column in the datagridview. You can edit it to your needs :=)

Private Sub DataGridView1_DataBindingComplete(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete

        Dim _DGV As DataGridView = DirectCast(sender, DataGridView)
        _DGV.Columns(_DGV.ColumnCount - 1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    End Sub
4advanced 23 Junior Poster in Training

Databind() is a function which needs to be called when binding data to a datagrid in ASP.NET !

Only use datasource when binding in Windows.Forms solutions!

yourGrid.DataSource = yourDataSource

If you had checked the posts on the first page you would have found out the solution....it has been mentioned a few times before!!!!

bajanpoet commented: Last post to me was pretty condescending, imho. I have tried to do what was requested, and I didn't appreciate the tone of the response. +0
4advanced 23 Junior Poster in Training

I really don't understand a thing about your question!

If you are asking for some help you really need to explain everything into details. We can't guess about what your goals are.....

4advanced 23 Junior Poster in Training

hmmm....did you checked that if you compile your application the base-codepages remain?
That's an option in visual studio....

4advanced 23 Junior Poster in Training

Any code in a code-behind page which could interrupt with your form?

4advanced 23 Junior Poster in Training

The way I should implement is : using the LostFocus event for the textboxes. After the lostfocus you can warn a user corresponding the maximum or minimum values needed. Second is creating yourself a class in which you calculate the FV.

code below:

Public Class Class1
    Private _FutureValue As Decimal
    Private _PresentVal As Decimal
    Private _Interest As Double
    Private _Period As Integer
   'just for remembering the formula (for me :=) )
    Private Const CN_Formula As String = "FV = PV * (1 + i / 100) ^ n"

    Public Property FutureValue() As Decimal
        Get
            Return _FutureValue
        End Get
        Set(ByVal value As Decimal)
            _FutureValue = value
        End Set
    End Property
    Public Property PresentVal() As Decimal
        Get
            Return _PresentVal
        End Get
        Set(ByVal value As Decimal)
            _PresentVal = value
        End Set
    End Property
    Public Property Interest() As Double
        Get
            Return _Interest
        End Get
        Set(ByVal value As Double)
            _Interest = value
        End Set
    End Property
    Public Property Period() As Integer
        Get
            Return _Period
        End Get
        Set(ByVal value As Integer)
            _Period = value
        End Set
    End Property
    Public Function Calculate() As Decimal
        Try
            Return Me.PresentVal * (1 + Me.Interest / 100) ^ Me.Period
        Catch ex As Exception
            Throw New ArgumentException("For some reason no calculation could be done!")
        End Try

    End Function

    Public Sub New()
        MyBase.New()
    End Sub
End Class

formcode:

Public Class Form1
    Private myCalc As Class1 = New Class1
    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        Try
            myCalc.PresentVal = CType(DirectCast(sender, TextBox).Text, Decimal)
        Catch ex As Exception …
4advanced 23 Junior Poster in Training

Sure you can, see the implementation below. This example is a copy/paste code from my project in which I added a class "ValidationInstance" which holds a collection of items which should be checked (or préfilled before the handler IsValid will be raisen).

Dim iPropertyCount As Integer = 0
        For Each PropertyItem As PropertyInfo In yourClass.GetType().GetProperties()
            Select Case iPropertyCount
                Case 1 To 10
                    'add the properties of this class to then validation instance

                    Dim strToAdd As String = String.Empty
                    If Not PropertyItem.GetValue(yourClass, Nothing) = Nothing Then
                        strToAdd = PropertyItem.GetValue(yourClass, Nothing).ToString()
                    End If
                    yourClass.ValidationInstance.ValidateRequired(PropertyItem.Name, _
                                                        strToAdd.ToString)

            End Select

            iPropertyCount += 1
        Next