SIGN UP MEMBER LOGIN:    
ARTICLE

Using a Disconnected DataTable to Display Records in GridView in ASP.NET

Posted by Abhimanyu Kumar Vatsa Articles | ASP.NET Programming October 10, 2011
In this post you will learn how to use a disconnected DataTable in ASP.NET to display records.
Reader Level:
Download Files:
 

Introduction

In this article we are going to take a look at a way to use a disconnected DataTable and will also display the records in GridView using this. In the later article, you will learn how to perform CRUD (Create Read Update Delete) operations using a disconnected DataTable. For the very first time a question will arise, what is a disconnected DataTable? Let's define it in few words.

Prerequisite

I am assuming that the article learner is aware of the basics of ADO.NET and fundamental configuration, however I will try to use fundamental steps also so that a beginner learner can also get this.

What is a disconnected DataTable?

A disconnected DataTable can be used to communicate between distributed applications or web services, especially when someone wants to revert back all operations (Create Update Delete) made on data. A disconnected DataTable supports multiple DataTable bindings and it also makes it possible to navigate forward and backward in a DataTable, will talk about this is later articles.

Create Database

First, create the sample database for our demonstration. Here is the screenshot of my SQL Server Express database; you need to create it in your application.

image002.jpg
 

In the above database table definition window I will be using the id column as the primary key and identity specification that will be increased by 1 each time automatically.

Create a ConectionString in Web.Config

In this demonstration we are going to store the connectionString setting in the web.config file. So, let's create the connectionString. Here is the one I am using.

<connectionStrings>
       <
add name="DatabaseConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

In the  above connectionstring setting I have attached its name to "DatabaseConnectionString1".

Default.aspx Page Desing

The scope of this article is to display the data in a GridView using a disconnected DataTable, so we just need a GridView control here. Here is the one I am using.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
    Width="229px">
    <Columns>
        <asp:BoundField DataField="id" HeaderText="ID" />
        <asp:BoundField DataField="friends" HeaderText="Friends" />
    </Columns>
</asp:GridView>

In the  above code, I am setting AutoGenerateColumns to false and also added two BoundFields that will point to the id and friends fields from the DataTable.

Now let's move next on to view the main logic of this disconnected DataTable.

Default.aspx.cs Page Code

Here, we are going to talk about each method and event handler one by one.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        InitializeDataAndGridView();
    }
}

Firstly, I am checking it's postback and if it is false then calling a method named InitializeDataAndGridView(), which will perform the next task.

private void InitializeDataAndGridView()
{
    PopulateData();
    LoadGridView();
}

In the above code, I am calling two more methods, one for populating the data and another for loading data into a container that is a GridView here for this demonstration.

Let's take a look at the PopulateData() method:

protected void PopulateData()
{
    SqlDataAdapter sqlDA = CreateAdapter();
    sqlDA.FillSchema(FriendseDataTable, SchemaType.Source);
    sqlDA.Fill(FriendseDataTable);
}

protected SqlDataAdapter CreateAdapter()
{
    String connStr = ConfigurationManager.ConnectionStrings["DatabaseConnectionString1"].ConnectionString;
    SqlConnection conn = new SqlConnection(connStr);
    SqlCommand cmd = new SqlCommand("SELECT * FROM Table1", conn);
    cmd.CommandType = CommandType.Text;
    SqlDataAdapter sqlDA = new SqlDataAdapter(cmd);
    return sqlDA;
}

public DataTable FriendseDataTable
{
    get
    {
        if (Cache["friendsDataTable"] == null)
            Cache["friendsDataTable"] = new DataTable("friendsDataTable");
        return (DataTable)Cache["friendsDataTable"];
    }
}

In the  above code, we are using a SqlDataAdapter instance to sqlDA and this code is playing main role in the disconnected model. Why, read on.

What is DataAdapter and all that stuff above?

A DataTable never has a live connection with a DataSource because the DataAdapter connects with the DataSource and executes the query and places the result in a DataTable. We don't need an open connection to use the DataAdapter.

The CreateAdapter method returns all resultant data back to the DataTable and here our DataTable instance is FriendsDataTable.

That's all for the short description on the PopulateData() method, now let's move to the  LoadGridView() method that will load our DataTable to GridView. Here is the code:

protected void LoadGridView()
{
    GridView1.DataSource = FriendseDataTable;
    GridView1.DataBind();
}

In the  above code, I am filling GridView1 with FriendDataTable, which has all records.

Please download the attached file and demonstrate it yourself. I hope you like this post. Please post your comments and feedbacks here. Love you. Thanks.

Login to add your contents and source code to this article
share this article :
post comment
 

you welcome

Posted by Abhimanyu Kumar Vatsa Oct 12, 2011

Quite useful. Thanks for sharing.

Posted by Mamta M Oct 12, 2011

you welcm

Posted by Abhimanyu Kumar Vatsa Oct 12, 2011

Very nice one abhimanyu.Thank you

Posted by karthik vasudevula Oct 11, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Team Foundation Server Hosting
Become a Sponsor