Archive
ASP.NET: Create user Control
In this article, we will be building a simple User Control to demonstrate how a ASP.NET User Control can be added into a ASPX page.
Assuming that you created an Empty Web Application from Visual Studio, you now create a new User Control by right-click on your web application > Add > New Item and name it MyUserControl.ascx. Then click Add.
Now, you have created your User Control. Now, lets put in some text so that we can see it in the web page later.
Next, we will add this User Control into our ASPX web page. First, you have to register your User Control on the top of your page, under the @Page declaration. You should add the @Register declaration like below.
<%@ Register src="UserControl/MyUserControl.ascx" tagname="MyUserControl" tagprefix="uc1" %>
The “src” property should be pointing to where your ASCX file is located. Then you can name the “tagname” and “tagprefix” property. By default, the “tagname” will be your User Control file name, and the “tagprefix” will be “uc1” if you are adding the first User Control in the page.
Next, you add the control into your page like how you add a Button or Label into your webpage. Add the following code into the Body.
<uc1:MyUserControl ID="MyUserControl1" runat="server" />
Your ASPX page code should look like the following.
Now, save and run your code. You will see that your User Control is loaded into the web page. You have just successfully added a custom User Control into your web page.
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.