Thursday, March 29, 2012

Populate 2 or more datagrids from one OleDBCommand

Hi All,

I wish to populate more than one datagrid from the same OleDBCommand. The
code I have is:

Dim objCmd As New OleDbCommand(strSql, objConn)

Then...

Me.dgTariffHolidayHomesBand1.DataSource = objCmd.ExecuteReader()
Me.dgTariffHolidayHomesBand1.Visible = True
Me.dgTariffHolidayHomesBand2.DataSource = objCmd.ExecuteReader()
Me.dgTariffHolidayHomesBand2.Visible = True

I get this error when the second call to objCmd.ExecuteReader() is called:
System.InvalidOperationException: ExecuteReader requires an open and
available Connection.

The reason for populating multiple grids from the same data, is that I am
calling ALL columns in the SQL, and then using (for example) columns A and
B
in DG1, C and D in DG2...and so on.

Surely I don't need a new recordset for each datagrid?

Simon.There are a couple problems with your approach.

First, the ExecuteReader method requires that you close and re-open the
connection, just as the code implies but you can't use a DataReader as the
DataSource for a DataGrid. You need something that implements IList or
IListSource. You can research both of those interfaces in the MSDN Library
to see what classes implement them.

Another problem is that you're making two queries to the database and
populating the DataGrids sequentially. What happens if the data changes
between calls? You can't be sure the data in the DataGrids will match.
What you need to do is get the data once, using a DataSet or even a
DataTable and set both DataGrids to use the same DataSource.

Hope this helps,

DalePres
MCAD, MCSE, MCDBA

"Simon Harris" <too-much-spam@.makes-you-fat.com> wrote in message
news:ODOqdixBFHA.1400@.TK2MSFTNGP11.phx.gbl...
> Hi All,
> I wish to populate more than one datagrid from the same OleDBCommand. The
> code I have is:
> Dim objCmd As New OleDbCommand(strSql, objConn)
> Then...
> Me.dgTariffHolidayHomesBand1.DataSource = objCmd.ExecuteReader()
> Me.dgTariffHolidayHomesBand1.Visible = True
> Me.dgTariffHolidayHomesBand2.DataSource = objCmd.ExecuteReader()
> Me.dgTariffHolidayHomesBand2.Visible = True
> I get this error when the second call to objCmd.ExecuteReader() is called:
> System.InvalidOperationException: ExecuteReader requires an open and
> available Connection.
> The reason for populating multiple grids from the same data, is that I am
> calling ALL columns in the SQL, and then using (for example) columns A and
> B
> in DG1, C and D in DG2...and so on.
> Surely I don't need a new recordset for each datagrid?
> Simon.

0 comments:

Post a Comment