Isnt DataTables and DataGrid binded?

Jun 18, 2009 at 4:47 PM

Hi

I have created a window which basicallty does this:

Dim dt As New System.Data.DataTable
        dt.Columns.Add("name")
        dt.Columns.Add("Number 1")
        dt.Columns.Add("Number 2")
        dt.Columns.Add("Result")
        For i As Integer = 0 To 3
            Dim rad As System.Data.DataRow = dt.NewRow()
            rad.Item(0) = "Name " & i
            rad.Item(1) = i
            rad.Item(2) = 3
            rad.Item(3) = CDbl(rad.Item(1)) + CDbl(rad.Item(2))
            dt.Rows.Add(rad)
        Next

        dg1.ItemsSource = dt.DefaultView

Now for the tricky part. When the data initilizes i whant the datagrid to behave like an Excel work sheet. I.e. when i change a value in the datagrid, it will automatically update the result in column nr 4.

This is what i had to do:

    Private Sub dg1_DataContextChanged(ByVal sender As System.Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs)
        For i As Integer = 0 To 3
            dt.Rows(i).Item(3) = CDbl(dt.Rows(i).Item(1)) + CDbl(dt.Rows(i).Item(2))
        Next
    End Sub

    Private Sub dg1_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        For i As Integer = 0 To 3
            dt.Rows(i).Item(3) = CDbl(dt.Rows(i).Item(1)) + CDbl(dt.Rows(i).Item(2))
        Next
    End Sub

 My question is, is there a simpler way than this or Im I stuck whith this solution?`

 

Regards Kenneth

 

 

 

Coordinator
Jun 23, 2009 at 5:24 AM

You can create a layer between the DataTable and the UI, essentially a business layer, where you can bind with the UI.  There you can do the calculated values instead of in your UI.

Jun 23, 2009 at 12:15 PM

Hi

Not that experienced with programming to know what you mean with a buisness layer. Could you give me a short excample?

Kenneth

 

Jun 27, 2009 at 9:50 PM

Why don't you just add an expression column?

for your third column try

dc = new DataColumn("Result")
dc.Expression = "[Number 1] + [Number 2]"

dt.Columns.Add(dc)

For all the options check the msdn documentation - in the index go to DataColumn.Expressions.

Jeremy

Jun 27, 2009 at 10:13 PM

Hmm

 

Im calculating standard deviation average value and numbers of data in the previous colums in my original application... This seems a little difficult to do by Expression

 

Kenneth