Bind Records to Gridview Button Click Event

The following code will bind the records returned from a Microsoft Access database to a Gridview control when the button 'Button1' is clicked and it's Click event is raised and the 'SearchCustomers' method run.

The Access database is called 'Customers' and has a table called 'tblCustomers'. The database is located in the folder 'H:\Inetpub\wwwroot\code\Customers.mdb'.

If the datareader 'DataReader' contains records returned from the database then the records are bound to the Gridview 'Gridview1" otherwise we have set the EmptyDataText property of the gridview to display the text "There are no records".

When the Page_Load event is run for the first time (If Page.IsPostBack=False) the Gridview's Visible property is set to 'false'. This makes sense as there will be no records to display atleast until the button has been clicked by the user.

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Data.Oledb" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Protected Sub SearchCustomers(ByVal s As Object, ByVal e As EventArgs)

    Dim Connection As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;" & _
    "Data Source=H:\Inetpub\wwwroot\code\Customers.mdb")
    Connection.Open()
    Dim Command As New OleDbCommand("Select * FROM tblCustomers", Connection)
    Dim DataReader As OleDbDataReader
    DataReader = Command.ExecuteReader   
    GridView1.DataSource = DataReader
    GridView1.DataBind()
    Connection.Close()
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
    If Page.IsPostBack = False Then
       GridView1.Visible = False
      Else
       GridView1.Visible = True
     End If
End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id=Head1 runat="server">
<title>List Customers</title>
</head>

<body>

<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="List Customers" OnClick="SearchCustomers" />
<asp:GridView ID="GridView1" runat="server" EmptyDataText="There are no records." / >
</div>
</form>

</body>
</html>

Get the best asp hosting provider from web-hosting-top.com and save up to 30%

Advertisements



MembersPro

MembersPro PayPal - ASP Membership software

Plug and play ASP membership script that integrates with PayPal to let you charge recurring membership fees.

Global ASP.NET Hosting Leader - Click Here