PDA

View Full Version : Create GridView using code?


Nelson9
09-06-2009, 10:04 AM
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

Mike_O
09-07-2009, 06:02 PM
Hey Nelson9,

Considering the way you're doing it, is almost right, but you also have to add your programmatically created control to the page (or should I say to another control). For example, let's say you have this tag on your page:
<div id="Div1" runat="server"></div>

Then on the server side, you add your GridView to this one something like this:
Div1.Controls.Add(GridView1)

And that should do it. I have to ask though...do you necessarily need to create the GridView programmatically? I mean, I understand that the sql statement needs to be dynamic, but why the GridView?

Regards,
Mike

Nelson9
09-08-2009, 04:02 PM
I have used gridview control from toolbox ut i wanted to know how to display the contents programically.

Mike_O
09-08-2009, 04:23 PM
Hey Nelson9,

Sorry, I'm a bit confused. You have the GridView control on your page already? If yes, what's throwing me off is that you are instantiating it in your code by saying:
Dim GridView1 As New GridView

That's why I figured you wanted to create the control programmatically as well, If I'm wrong about that, you should remove that line from your code. The GridView is already there. Now, if you're asking how to include the bound fields inside the GridView, it would be something like this:
<asp:GridView ID="GridView1" runat="server">
.
.
<%#Eval("[your field name]")%>
.
.
</asp:GridView>

Am I missing something?

Regards,
Mike