Dynamic GridView Series - 1.Simple Gridview Binding at runtime
Requirement 1
===========
We need to bind the data dynamically to the GridView of ASP.NET 2.0
Let's create a new ASP.NET Web site.
Add the following lines just after your <configuration> tag in the web.config. I will be working with the "pubs" database all the time. Better to have it in the web.config. Ensure that you don't have multiple <appSettings> tag in your web.config, else the application won't compile at all.
<appSettings>
<add key="ConnectionInfo" value="server=(local);database=Pubs;user id=sa;password="/>
</appSettings>
1) Create a new Page called "BasicDataGrid.aspx"
2) Ensure that Language="Visual Basic" and "Place Code in Sepearte file" checkbox is unchecked.
3) Drag and drop a Placeholder control on the form and paste the following in the "Source View"...
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Dim gvGrid As GridView
Dim strConn As String = ConfigurationSettings.AppSettings("ConnectionInfo")
Dim strCommand As String = "select au_id as Author_ID, au_lname as Last_Name," & _
" au_fname as First_Name, phone as Phone_Number, state as State from authors"
Protected Sub Page_Load( _
ByVal sender As Object, _
ByVal e As System.EventArgs _
)
gvGrid = New GridView()
Dim tblData As DataTable
tblData = GetData(strCommand, strConn)
'
gvGrid.DataSource = tblData
gvGrid.DataBind()
PlaceHolder1.Controls.Add(gvGrid)
End Sub
'
Private Function GetData(ByVal strCommand As String, _
ByVal strConn As String _
) As Data.DataTable
'
Dim adpSQLAdapter As New SqlDataAdapter(strCommand, strConn)
Dim tblData As New DataTable()
'
adpSQLAdapter.Fill(tblData)
Return tblData
End Function
</script>
<html xmlns="https://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Dynamic GridView bound to a simple dataset</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
</html>
4) Open Solution Explorer, right click on "BasicDataGrid.aspx" and select "Set as Start Page" in the menu
5) Click on Debug -> Start and you should be able to see a very simple table of Data (with no Formatting) from the Database.
Comments
Anonymous
May 04, 2006
:)Anonymous
December 18, 2006
Please change your title in the article because Google thinks you are using a DataSet when you are actually using DataTable.Anonymous
December 18, 2006
Thx for the example thoughAnonymous
August 24, 2008
How can I implement paging and sorting in dynamically generated gridview? Please reply waiting for reply......Anonymous
March 10, 2014
A gridview tutorial that covering most of the operations.. asp.net-informations.com/.../asp-gridview.htm bona.