Archive
Databinding GridView programatically
In my previous post, I’ve showed how to bind data to GridView using SqlDataSource. Here, I’ll show how to bind data to GridView using code behind.
Assumptions:
I assume you already have a ready database that have a Customers table. Also you have pre-define a connection string in your web.config file.
Code for ASPX page:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebDemo_CS.Web.Data.GridView.DatabindProgramatically.Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Databind GridView Programatically</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1>
Databind GridView Programatically</h1>
<asp:Label runat="server" ID="Label1" ForeColor="Red" />
<br />
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="true">
</asp:GridView>
</div>
</form>
</body>
</html>
Code for C#:
protected void Page_Load(object sender, EventArgs e)
{
// This example uses Microsoft SQL Server and connects
// to the Northwind sample database. The data source needs
// to be bound to the GridView control only when the
// page is first loaded. Thereafter, the values are
// stored in view state.
if (!IsPostBack)
{
// Declare the query string.
String queryString = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]";// Run the query and bind the resulting DataSet
// to the GridView control.
System.Data.DataSet ds = GetData(queryString);
if (ds.Tables.Count > 0)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
else
{
Label1.Text = "Unable to connect to the database.";
}
}
}System.Data.DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;System.Data.DataSet ds = new System.Data.DataSet();
try
{
// Connect to the database and run the query.
System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString);
System.Data.SqlClient.SqlDataAdapter adapter = new System.Data.SqlClient.SqlDataAdapter(queryString, connection);// Fill the DataSet.
adapter.Fill(ds);
}
catch (Exception ex)
{
// The connection failed. Display an error message.
Label1.Text = "Unable to connect to the database.";
}return ds;
}
Code for VB.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
‘ This example uses Microsoft SQL Server and connects
‘ to the Northwind sample database. The data source needs
‘ to be bound to the GridView control only when the
‘ page is first loaded. Thereafter, the values are
‘ stored in view state.
If Not IsPostBack Then‘ Declare the query string.
Dim queryString As String = "Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"‘ Run the query and bind the resulting DataSet
‘ to the GridView control.
Dim ds As DataSet = GetData(queryString)
If (ds.Tables.Count > 0) Then
GridView1.DataSource = ds
GridView1.DataBind()
Else
Label1.Text = "Unable to connect to the database."
End IfEnd If
End SubProtected Function GetData(ByVal queryString As String) As DataSet
‘ Retrieve the connection string stored in the Web.config file.
Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Dim ds As New DataSet()Try
‘ Connect to the database and run the query.
Dim connection As New System.Data.SqlClient.SqlConnection(connectionString)
Dim adapter As New System.Data.SqlClient.SqlDataAdapter(queryString, connection)‘ Fill the DataSet.
Adapter.Fill(ds)Catch ex As Exception
‘ The connection failed. Display an error message.
Label1.Text = "Unable to connect to the database."
End TryReturn ds
End Function
Conclusion:
Data bind data into GridView from code behind provides more flexibility as you can control the data to be selected from the database dynamically.
Databinding GridView using SqlDataSource
The GridView control in ASP.NET is a control that displays the data that you selected from the database in a form of a table where each row represents a record in the database. GridView also allows you to select, update, delete, and sort the data.
In addition, GridView also allows you to customize how the data is to be represented to the user when the data is binded from the database.
Here, I’ll show you how to bind data into the GridView control using SqlDataSource control as the data source.
Assumptions:
I assume you already have a ready database that have a Customers table. Also you have pre-define a connection string in your web.config file.
Code for ASPX Page:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="Default.aspx.vb" Inherits="WebDemo_VB.Web._GridView_SqlDataSource_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False" DataKeyNames="CustomerID"
DataSourceID="SqlDataSource1" EnableModelValidation="True">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID" InsertVisible="False" ReadOnly="True" SortExpression="StaffID" />
<asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
<asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="PostalCode" HeaderText="PostalCode" SortExpression="PostalCode" />
<asp:BoundField DataField="Country" HeaderText="Country" SortExpression="Country" />
</Columns>
</asp:GridView>
<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
SelectCommand="[CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
The code above shows a simple method on how to data bind the GridView to display information from the Customers table in the database. This is the most simple way of data binding a GridView control.
Note: For advanced data binding and customization method, please wait/see the later post.
Getting ConnectionStrings value from code behind
When you do wants to get some data from a database to show it on your ASP.NET web application, you will need to use a connection string to connect to the database. This string is very important because, at most conditions, you will be using this string again and again across the entire application. Therefore, you can utilize the ConnectionStrings tag in the web.config file to store your predefined connection strings.
Well, some programmers will say “Why do I need to store it in the web.config file? I can just code it in my code behind codes and it will still work the same.”. Yes, it will still work the same. But that is only suitable for a mini web application that does not require much connection to the database. However, if it’s a big web application and the connection string values have to be changed, the programmers will spend a long time just to find and replace the existing connection string to the new string.
Therefore, it’s advised to always store a connection string in the web.config file and get its value from here. Below, I will show you how to get the connection string values from the ConnectionStrings tag in the web.config file.
Code in web.config:
<connectionStrings>
<add name="MyConnectionString" connectionString="Your connection string here" providerName="System.Data.SqlClient" />
</connectionStrings>
Code for C#:
System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
Code for VB.NET:
System.Configuration.ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
From the sample above, I’ve named my connection string to “MyConnectionString”. For the connectionString values which I’ve written as “Your connection string here”, you will have to replace it with a proper connection string. You can find more about connection string from http://connectionstrings.com/. As for the providerName, you have to put the namespace of the data connection class. In this case above, “System.Data.SqlClient” will be connecting to Microsoft SQL Server.