Create GridView using code?

Discussion in 'C#' started by sxcnelson, Sep 2, 2009.

  1. #1
    I am a complete newbie to asp.net.I am trying to create gridview using code.
    But when i run the program i get blank page nothing else.Here is the code:


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim constr As String
    Dim data As OleDbDataAdapter
    Dim GridView1 As New GridView
    Dim ds As New DataSet

    constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\db.mdb"
    Dim con As New OleDbConnection(constr)
    con.Open()
    data = New OleDbDataAdapter("select * from Table1", con)
    data.Fill(ds)
    GridView1.DataSource = ds.Tables("Table1")
    GridView1.DataBind()

    End Sub
     
    sxcnelson, Sep 2, 2009 IP
  2. marshalprince

    marshalprince Peon

    Messages:
    435
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #2
    data = New OleDbDataAdapter("select * from Table1", con) is wrong

    fill ds

    ds = New OleDbDataAdapter("select * from Table1", con)
     
    marshalprince, Sep 3, 2009 IP
  3. sxcnelson

    sxcnelson Peon

    Messages:
    211
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    still problems
    can anyone paste the corrected code
     
    sxcnelson, Sep 5, 2009 IP
  4. rahulwb

    rahulwb Peon

    Messages:
    32
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    u didn't register the control on page..How will ir display when u don't have gridview on form.
    Either register control before page load event or easy task is

    1. remove only this line - Dim GridView1 As New GridView - from your aspx.vb code
    2. go to ur .aspx page switch to design view, from toolbox on left drag and drop gridview.
    3. switch to source view check if gridview is in aspx page with id gridview1
    3. run ur code
     
    rahulwb, Oct 5, 2009 IP
  5. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #5
    You need to add the control to the page. Something like:
    
    Form1.Controls.Add(GridView1)
    
    Code (markup):
    However, this will add the control to the end of the page. If you wish to insert it somewhere within the page you can use a PlaceHolder (<asp:placeHolder) and then add the control to that using the same method:
    
    myPlaceHolder.Controls.Add(GridView1)
    
    Code (markup):
    you could also achieve the same result using a 'Label' or 'Panel' as the placeholder...
     
    Last edited: Oct 6, 2009
    camjohnson95, Oct 6, 2009 IP