Refreshing DataTable

S

Simon

Hi All,

I have a DataGrid bound to a DataTable. Every once in a while I need
to refresh the data in the table so that the updated data is displayed
in the DataGrid. Here's how I am attempting this:

'clear datatable
datatbl.Rows.Clear()

If PLCCount() <> 0 Then
'add rows to datatable containing PLC info
For p = 0 To PLCCount() - 1
Dim rowinfo As DataRow
rowinfo = datatbl.NewRow()
rowinfo("ID") = plcID(p)
rowinfo("Road") = PLCRoadName(p)
rowinfo("Start Time") = MyDate(plcStartTime(p))
rowinfo("End Time") = MyDate(plcEndTime(p))
rowinfo("Location") = plcLocationDescription(p)
rowinfo("Cause") = plcCause(p)
'add info to datatable
Try
'out-of-bounds error here
datatbl.Rows.Add(rowinfo)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
Next p
'bind to datatable to datagrid
grdClosures.DataSource = datatbl
End If

I clear the rows in the DataTable and re-populate. However, when I try
and add the new rows i get an out-of-bounds exception in the Add
function.

This has something to do with the fact that I clear the rows and then
create new ones but I don't know nor understand why this is a problem.

Can anyone help?

Many thanks

Simon
 
C

Cor Ligthert

Simon,

I made this sample now. I don't set it on our site it is to simple for my
opinion. Can you have a look for yourself what that means accoording your
code.

At least there is no reason to set that datasource again in your code as you
do now.

\\\
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Dim dt As DataTable = CreateTables()
dt.DefaultView.Sort = "State"
DataGrid1.DataSource = dt
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim dt As DataTable = DirectCast(DataGrid1.DataSource, DataTable)
'The row above is to set the datatable not global not something
accoording your problem
dt.LoadDataRow(New Object() {"Michael Coles", "New Jersey"}, True)
End Sub
'To have a table to use is one created below
Private Function CreateTables() As DataTable
Dim dt As New DataTable("Persons")
dt.Columns.Add("Name", GetType(System.String))
dt.Columns.Add("State", GetType(System.String))
dt.LoadDataRow(New Object() {"Ken Tucker", "Florida"}, True)
dt.LoadDataRow(New Object() {"Cor Ligthert", "Holland"}, True)
Return dt
End Function
///
I hope this helps,

Cor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top