Convert data source to Data view

In my aspx page I populate the gridview control using OleDbDataReader. And in GridView1_RowCreated, I try to assign the datasource to a dataview, but it gives me an error "Unable to cast object of type 'System.Data.OleDb.OleDbDataReader' to type 'System.Data.DataView'."

Here is the code

Sub displayitems()
        Dim strSQL As String
            strSQL = "Select ItemId,Description1 + '<BR>' + Description2 + '<BR>' + Description3 as Description , " _
            & "format(Item.UnitPrice,'00.00') as Price,Qty as [In Stock] from Item"

            Dim oleCmd As OleDbCommand = New OleDbCommand(strSQL, oleDbConn)

            Dim myReader As OleDbDataReader
            myReader = oleCmd.ExecuteReader()

            If myReader.HasRows = True Then
                grdItems.DataSource = myReader
     End If
End Sub

Protected Sub grdItems_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdItems.RowCreated
        Dim dv As DataView = grdItems.DataSource
        Dim dcCol As DataColumn
        Dim dc As DataColumnCollection = dv.Table.Columns
        Dim intRowId As Integer
        Dim strColumn As String, strScript As String

        Dim i As Integer = 0
        For Each dcCol In dv.Table.Columns
    'Do something
End Sub

The statement Dim dv As DataView = grdItems.DataSource gives me the error.

Your valuable feedback is greatly appriciated

12/30/2005 7:28:04 PM 72751 articles. 3 followers. Follow

2 Replies

Similar Articles

[PageSpeed] 44

The reason it's not working is exactly what you're seeing in the exception error message: You're using a DataReader, but you want a DataView instead. The solution is to simplly always use a DataView. In your displayitems() method you need to create a DataSet and fill it with an OleDbDataAdapter.

The code is something like this:

DataSet myData = new DataSet();

OleDbDataAdapter dataAdapter = new OleDbDataAdapter(oleCmd, oleDbConn);


And then instead of executing the command manually (it gets executed automatically when you call Fill()), bind the grid like this:

grdItems.DataSource = myData.Tables[0].DefaultView;


Now that you're actually using a DataView, you can always use it from other methods.



12/30/2005 8:27:36 PM
Thanks a  million. Much appriciated.
12/30/2005 8:32:21 PM

Similar Artilces:

Data presentation control in another Data presentation control
 Hello,I want to make a menu with datalist or gridview control.Basically,the menu will be like this,Categories     Sub Categories.For example, for COMPUTING category there will be NOTEBOOKS DESKTOPS etc.There will be a image for CATEGORIES and linkbuttons with Subcategories.If I put a datalist inside a datalist and a link button inside the second datalist visually it satisfies my need.However,CommandArguments come from database to linkbutton.Andwhen one of these command buttons is cliked it must go to proper page.I dont know how to wrie an event_handler ,specifically, for...

data, data, data
Hello, I need some advice on the best method to keep a database updated in this scenario. I have a local Solomon SQL Server where we keep our inventory. I want to build an application that will be hosted at a remote hosting location which provides a SQL database. I want to build the application to allow clients to access the inventory items and make requests based on the remote SQL data. The order will be sent to our fulfillment department via email; they will fiill the request and ship.  I'm not sure the method to do this while keeping the data current on the remote and the l...

Bind Data to an Image Control not in a Data Presentation Control
I've been searching for two days but I don't really know what to search for.I'm making a site for a photographer.  The Default.aspx page displays Albums by showing a title, image and description from the database table Albums. Click an album to view the contents and it passes the QueryString which is AlbumName.  The ViewAlbum.aspx page uses the QueryString to display an UpdatePanel holding a Large Image and a Repeater full of dynamically filled ImageButtons for thumbs.  Both are from the database table Photos and are retrieved using an ObjectDataSource. Click the ...

How to validate Session Data before FormView and Object Data Source Controls the session data
I have a FormView control as well as two object data sources on a webpage.  Some of the data that is used by these controls comes from session objects that were loaded in a different page.  I want to be able to validate this session data before the FormView or the Object Data Sources uses them, so I added the following piece of code into my Page_Load: if (!IsPostBack){    ValidateSessionData();} The ValidateSessionData throws an error if the session data is not correct (ie. the previous web page sent this page bad data).   Unfortunately throwi...

Data Caching with a Data Source Control?
Hi,I'm using a DetailsView and SqlDataSource controls to retrieve and update records from database. And I use SqlCacheDependency for data cacheing. I've done correct configuration for SqlCacheDependency. Although it is, updated records are not shown correctly. It shows old records. But when I reduce pollTime in web.config (pollTime=1000), the result is up-to-date. Here is my question. 1. Does it affect SQL server performance? By reduction pollTime, AspNet_SqlCachePollingStoredProcedure is running at regular interval when I traced with SQL profiler.2. Whether it affects or not, could ...

Data presentation without a data control
The Gridview and Formview controls provide good functionality in some circumstances but are clumsey in others. As a newbie to .NET I was wondering if its appropriate to do databinding with textboxes and other data controls outside of one of the new data controls (formview, gridview, etc). Or is it a new standard to always use one of the new data controls. If the answer is yes, would you still use an SQLDatasource, or would you set up the connection in code? And, how would you deal with the syntax? In the Formview we have: <asp:TextBox ID="fnameTextBox" runat="server" ...

Data Presentation Controls and complex data+logic
I'd like to know how people solve problem of binding complex data to data presentation controls. As we all know, real life is not as simple as webcasts etc. assume.Lets say we have something like this.List<Person> liPerson = PersonFactory.GetAllPersons();List<Company> liCompany = CompanyFactory.GetAllCompany();And I want a table something like this:Microsoft      Bill      JohnIBM      Ted      CharlesNokia      Matti Is there a generic solution to...

Testing Data Sources to ensure valid data for controls.
Lets say you have a form with several DropDownLists on the page each bound to different SQL data sources to retrieve the data.  How can you test if the data sources are empty or have no records to prevent the dropdown lists from erroring out due to referencing null data? just use the DataBound event handler: write the OnDataBound="your_handler" as attribute of your DropDownLists then, write the handler code for example (C#):   protected void your_handler(object sender, EventArgs e) { if (((DropDownList)sender).Items.Count == 0) { ...

how to htmlencode data when using data controls to display data
Hi Lets say you are displaying a colllection of records in a gridview and you want to make sure all of the rows and columns are html encoded before you display them, how can can you get the gridview to do this automatically? I don't want to have to create a template for each bound column. Thanks very much andrea Hi Andrea, I believe there is a "HtmlEncode" property on each column that you can set.  By default I believe it is set to true.  You can pull up the column editor by selecting the "edit columns" task, and then select the columns in the botton left of the dialog to see...

Retrive the Data from Data base using hyperlink in a grid view and populating in Controls(Textbox,DDL,Grid View) in another page
  Hello Guys,                  I have a Grid View in one page connected to a DB with multiple columns.Only 5 columns are displayed in the grid view and the grid view has a hyper link.When I click the hyper link(in PAGE1),I must navigate to other page(PAGE2) where there are many controls(Text Box,DDL's and Grid Views).1)I want to populate these controls when the hyper link is clicked.2)I have Grid Views in page 2 which are even connected to other tables which are connected to this table with keys, ev...

Bind a repeater to two data sources and dispaly 2nd data source data in alternative item row
Hi, Can you please tell me how to bind a single repeater control to two sql data sources and display the 1st data source data in the ItemTemplate row and the 2nd data source in the AlternativeItemTemplate row item. Please note, the data fields in my data sources are the same but I need to be able to distinguish between the two in the repeater. I hope someone can help. Cheers Mark  can you post the selects you are trying to do?the amazing real A pak i am giving you an example you can accomplish your task same this wayyour gridview at desing time looks like this<itemTempl...

Data Data :|
Ok, i have a very simple access database called score with just one table called high. This is just going to be used to keep the current score of a higher scorer and there name However, when the page loads i want the user to see this current high score and the persons name, but just one record i only ever want this to hold one record aswell..When the user finish’s the game there score is currently presented to them, when this happens i would like to connect to the database and check weather there score is higher than the current score (may have changed since they loaded page...

Data or Data
I pronounce it "data". HTH I pronounce it dAta and data. Depends upon my mood and the context it's in. Like I preserve dAta, but i lose data. :P Matthew wrote: > I pronounce it dAta and data. Depends upon my mood and the context it's > in. Like I preserve dAta, but i lose data. :P Lt Commander D "ay" ta. Nuff said. In fact he corrected Dr Pulaski when she called him D "ah" ta. D ay ta, d ah ta, what's the difference? One is my name... the other is not. :) <-geek > > Lt Commander D "ay&quo...

Tracing data controls within data controls
I have a problem with tracing data controls within data controls. Below are the codes and the trace statements. Can anyone help me? Your help is very much appreciated. : : : private void InitializeComponent() { this.DataGrid1.ItemDataBound+=new DataGridItemEventHandler(DataGrid1_ItemDataBound); this.Load += new System.EventHandler(this.Page_Load); } #endregion private void DataGrid1_ItemDataBound(object sender, DataGridItemEventArgs e) { DropDownList Dropdownlist1 = (DropDownList)e.Item.Controls[2].FindControl("D...

Web resources about - Convert data source to Data view -

List of converts to Buddhism - Wikipedia, the free encyclopedia
Ajahn Brahm (born 1951), Religious teacher and student of the late Thai monk Ajahn Chah . Currently he is the abbot of the Bodhinyana Monastery, ...

Facebook Timeline For Pages: 8 Million Converts, 29 Million To Go
... reach to 98 percent of users who liked its page, as well as to double its engagement rate, during a 28-day period. Dr. Pepper hasn’t yet converted ...

Facebook stock roundup: Execs offload more stock, directors convert shares
... Bowles, the former co-chair of the now-defunct National Commission on Fiscal Responsibility and Reform, and Reed Hastings, Netflix CEO, converted ...

How to Convert Leads Into Buying Customers - The 9 Step Sales Process EVERYONE Should Use
... School of Business in Toronto on the topics of Sales and Entrepreneurship. I shared with them the sales process that I find How to Convert Leads ...

Bitcoin : Should I convert my savings to Bitcoin?
Answer (1 of 7): You should think of this question as "Should I invest all my savings in Bitcoin?", and not "Should I have my savings denominated ...

Coordinates - Calculate and Convert a Position on the App Store on iTunes
Get Coordinates - Calculate and Convert a Position on the App Store. See screenshots and ratings, and read customer reviews.

Catholics should not convert Jews, says Vatican, in push against anti-Semitism
... 50 years since the Vatican's repudiation of the concept of Jewish guilt for Jesus' death.  Vatican City: Catholics should not try to convert ...

Today’s apps gone free: BlockBear, Stock Grader, PDF Smart Convert and more
Block ads and other annoying content, take the emotion out of investing, and convert almost anything into a PDF with todays collection of apps ...

Ford patents rear wheel that converts into a unicycle
Filed under: Government/Legal , Green , Ford , Green Driving , Motorcycle , Electric Ford is thinking about allowing drivers to remove a rear ...

How to convert your old VHS tapes to DVD with this software
Remember those old VHS tapes you have sitting in the corner? Convert them into DVDs with this affordable software so you can easily watch them ...

Resources last updated: 1/22/2016 5:17:08 AM