Logo

Navigation
  • Home
  • Services
    • ERP Solutions
    • Implementation Solutions
    • Support and Maintenance Solutions
    • Custom Solutions
    • Upgrade Solutions
    • Training and Mentoring
    • Web Solutions
    • Production Support
    • Architecture Designing
    • Independent Validation and Testing Services
    • Infrastructure Management
  • Expertise
    • Microsoft Development Expertise
    • Mobile Development
    • SQL Server Database and BI
    • SAP BI, SAP Hana, SAP BO
    • Oracle and BI
    • Oracle RAC
  • Technical Training
    • Learn Data Management
      • Business Intelligence
      • Data Mining
      • Data Modeling
      • Data Warehousing
      • Disaster Recovery
    • Learn Concepts
      • Application Development
      • Client Server
      • Cloud Computing Tutorials
      • Cluster Computing
      • CRM Tutorial
      • EDI Tutorials
      • ERP Tutorials
      • NLP
      • OOPS
      • Concepts
      • SOA Tutorial
      • Supply Chain
      • Technology Trends
      • UML
      • Virtualization
      • Web 2.0
    • Learn Java
      • JavaScript Tutorial
      • JSP Tutorials
      • J2EE
    • Learn Microsoft
      • MSAS
      • ASP.NET
      • ASP.NET 2.0
      • C Sharp
      • MS Project Training
      • Silverlight
      • SQL Server 2005
      • VB.NET 2005
    • Learn Networking
      • Networking
      • Wireless
    • Learn Oracle
      • Oracle 10g
      • PL/SQL
      • Oracle 11g Tutorials
      • Oracle 9i
      • Oracle Apps
    • Learn Programming
      • Ajax Tutorial
      • C Language
      • C++ Tutorials
      • CSS Tutorial
      • CSS3 Tutorial
      • JavaScript Tutorial
      • jQuery Tutorial
      • MainFrame
      • PHP Tutorial
      • VBScript Tutorial
      • XML Tutorial
    • Learn Software Testing
      • Software Testing Types
      • SQA
      • Testing
  • Career Training
    • Career Improvement
      • Career Articles
      • Certification Articles
      • Conflict Management
      • Core Skills
      • Decision Making
      • Entrepreneurship
      • Goal Setting
      • Life Skills
      • Performance Development
      • Personal Excellence
      • Personality Development
      • Problem Solving
      • Relationship Management
      • Self Confidence
      • Self Supervision
      • Social Networking
      • Strategic Planning
      • Time Management
    • Education Help
      • Career Tracks
      • Essay Writing
      • Internship Tips
      • Online Education
      • Scholarships
      • Student Loans
    • Managerial Skills
      • Business Communication
      • Business Networking
      • Facilitator Skills
      • Managing Change
      • Marketing Management
      • Meeting Management
      • Process Management
      • Project Management
      • Project Management Life Cycle
      • Project Management Process
      • Project Risk Management
      • Relationship Management
      • Task Management
      • Team Building
      • Virtual Team Management
    • Essential Life Skills
      • Anger Management
      • Anxiety Management
      • Attitude Development
      • Coaching and Mentoring
      • Emotional Intelligence
      • Stress Management
      • Positive Thinking
    • Communication Skills
      • Conversation Skills
      • Cross Culture Competence
      • English Vocabulary
      • Listening Skills
      • Public Speaking Skills
      • Questioning Skills
    • Soft Skills
      • Assertive Skills
      • Influence Skills
      • Leadership Skills
      • Memory Skills
      • People Skills
      • Presentation Skills
    • Finding a Job
      • Etiquette Tips
      • Group Discussions
      • HR Interviews
      • Interview Notes
      • Job Search Tips
      • Resume Tips
      • Sample Resumes
 

ASP.NET Using the DataList and Repeater, Datagrid Controls

By Exforsys | on March 26, 2005 |
ASP.NET

In this tutorial of Week 6 we will be learning about Overview of List-Bound Controls, Creating a Repeater Control, Creating a DataList Control, Introduction to the DataGrid, Setting Up the DataGrid , Using Advanced DataGrid Features and Adding Advanced Features.



Overview of List-Bound Controls



As we have seen in the previous tutorials that Asp.net ships with many controls. We already discussed different types of buttons, validation controls and the calendar controls. But the most power of Asp.net comes with the Databound controls. Databound controls are those controls which can be binded to any data source. They are also known as complex controls as well as databound controls. In this tutorial we will see some of the most widely used databound controls.

Creating a Repeater Control(Sample1.aspx)

Let’s start with the Repeator control. Also keep in mind that all these controls are also known as the templated controls since their design is based on templates. Repeator control is used when we like to do our own formatting which means it is used in the cases where we like to make our own databound design control which may contain controls that we like.

In order to use the Repeator control you can just drag and drop the control on the webform. When you drop it will look something like this:

Now as you see that the repeator control is also telling you that if you don’t like what you see now you can always change it by using the html view of the page

Let’s see how we can do that so I went in the html view and changed the Repeator html code to this.





ItemTemplate tells the repeator control that what each item will be like in the repeator control. In the ItemTemplate we declared a button. Now switch back to the design view and you will see this:

So you see it just created several buttons for you since they were placed in the item template. There are also other types of templates like AlternatingItem and HeaderTemplate and FooterTemplate. Let’s see an example where we use all of them:









 

This is the Header




This is the footer




 

This is the Header




This is the footer




 

Now let’s see when I switch back to the design view what will I see:

Pretty cool right 🙂 I know

Lets see some other types of databound controls.

{mosgogole}

Creating a DataList Control

DataList is basically a control which you would like to use it when you are making a shopping cart or maybe when you are developing a photo album. Let me show you an image and than you will have better idea of what I am talking about.

Let’s make a simple DataList control (Sample2.aspx)

Just drag and drop a datalist control on the form. Right click the control and select Edit Template link at the bottom and select Item templates. Now you will see a visual designer where you can add anything in the item template section. You can even drag any control on the item template field. Let’s drag a textbox and see what happens. When you drag a textbox and switch back to the design view you will see 5 textboxes in a flowlayout. You can also set them in horizontal layout by using the RepeatDirection property.

Since, this control is similar to the repeator control I will not talk about this more and switch to DataGrid control which is perhaps the most widely used Data Bound control

Creating and using a datagrid control:

Setting up the Datagrid:

Lets first set up our datagrid.

  1. Drag and Drop the datagrid control from your toolbox to the webform.
  2. The datagrid will appear as a simple table.
  3. You can make the datagrid pretty by selecting the Auto format features.

Okay your datagrid is set up, lets add some columns.

Adding the Bound Columns:

Adding the bound colums in the datagrid is pretty simple.

  1. Right click on the datagrid and select Property Builder.
  2. Click on the Columns tab and uncheck "Generate columns automatically".
  3. Add three bound columns, give the columns some name in the column name field. And finally add the edit,update,cancel buttons which can be found under the button option.

Note: Please also note that the button type should be link button or else it wont work.

Storing the database connection

In this demo I am storing the database connection in the Web.config file. The database name is DBSnippets, which has one table known as tblPerson. Here is the web.config file.





Okay till now we have made the Datagrid and also saved the connection string in the web.config file. Now the time has come to code and handle the events.

Lets first make the BindData method which will retrieve the contents from the database and bind it on the screen. This will be one of the most important methods since it will be called whenever the page is loaded for the first time.

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindData();
}
}

As you see the BindData method is called when the page is not posted back. Now lets see the BindData method in details.

public void BindData()
{
SqlCommand myCommand = new SqlCommand("SP_SELECT_PERSONS",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
myAdapter.Fill(ds,"tblPerson");
myConnection.Open();
myCommand.ExecuteNonQuery();
myDataGrid.DataSource = ds;
myDataGrid.DataBind();
myConnection.Close();
}

Explanation of the BindData method:

  1. First we make a SqlCommand object and named it myCommand. The SqlCommand object takes a stored procedure as an input and the SqlConnection.
  2. We feed the command object to the DataAdapter object named as myAdapter.
  3. A dataset is declared which is filled with the result of the Stored procedure.
  4. myDataGrid.DataBind() binds the datagrid to the page. Don’t forget to bind the grid or else it won’t be displayed.
  5. Later we opened the connection and execute the query.

Now Lets see the stored procedure.

Stored Procedure:

CREATE PROCEDURE SP_SELECT_PERSONS
AS
SELECT * FROM tblPerson GO

As you can see that the above Stored Procedure is pretty simple. All we are doing is we are just selected all the columns from the table person.

Lets now make the Edit method which will display textboxes inside the datagrid so that a user can insert data. This sort of editing is also known as Inline editing.

Making datagrid editable is pretty simple. All you to do is to code few lines in the EditCommand event of the datagrid. You can view all the events supported by DataGrid by selecting properties and than selecting the Thunder/Flash yellow sign at the top of the properties window.

Lets call our Edit DataGrid event Edit_DataGrid.

private void Edit_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// We use CommandEventArgs e to get the row which is being clicked
// This also changes the DataGrid labels into Textboxes so user can edit them
myDataGrid.EditItemIndex = e.Item.ItemIndex;
// Always bind the data so the datagrid can be displayed.
BindData();
}

When the Edit link button is clicked your DataGrid will look something like this:

As you see when you click the edit link the update and the cancel link button automatically appears.

Lets now see the code for the Cancel Event. Cancel event is used when you are in the edit mode and you change your mind about not to edit. So you click the cancel link button and the Datagrid returns back to its orginal condition.

private void Cancel_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
// All we do in the cancel method is to assign ‘-1’ to the datagrid editItemIndex
// Once the edititemindex is set to ‘-1’ the datagrid returns back to its original condition
myDataGrid.EditItemIndex = -1;
BindData();
}

Okay now we come to a slightly difficult step. We will carefully look at the Update method and see how it works.

private void Update_DataGrid(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
System.Web.UI.WebControls.TextBox cName = new System.Web.UI.WebControls.TextBox();
cName = (System.Web.UI.WebControls.TextBox) e.Item.Cells[1].Controls[0];
SqlCommand myCommand = new SqlCommand("SP_UpdatePerson",myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add(new SqlParameter("@PersonName",SqlDbType.NVarChar,50));
myCommand.Parameters["@PersonName"].Value = cName.Text;
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
myDataGrid.EditItemIndex = -1;
BindData();
}

Lets now dig into this method and see whats going on.

  • The name of the method as you can see is Update_DataGrid, this event is fired when you click the update link button which appears after clicking the edit button.
  • We declare a variable of TextBox type and call it cName. The reason of declaring a TextBox is that the value that we want is inside the TextBox which is inside the DataGrid control.
  • Later we made the SqlCommand object which takes stored procedure "SP_UpdatePerson", which will be discussed afterwords.
  • After marking the command object with the stored procedure we passed the parameter which is PersonName.
  • Finally we execute the Query and set the editItemIndex property of the DataGrid ‘-1’ which will bring the datagrid back to its original form i.e without any textboxes.
  • Don’t forget to bind the datagrid.

Update Stored Procedure

CREATE PROCEDURE SP_UpdatePerson
@PersonName nvarchar(50)
AS
UPDATE tblPerson SET PersonName = @PersonName WHERE PersonName = @PersonName;

CREATE PROCEDURE SP_UpdatePerson
@PersonName nvarchar(50)
AS
UPDATE tblPerson SET PersonName = @PersonName WHERE PersonName = @PersonName;

Selecting Item from the Datagrid:

Another cool feature of the Datagrid control is that you can select any row from the datagrid and it will be displayed as the highligted row in the grid.

The highlight row event is called SelectedIndexChanged event. The event is called when the select column is clicked. The select column can be added to the datagrid using the property builder, just like we added "edit/cancel/update" link buttons.

// This event is fired when the Select is clicked
private void Select_DataGrid(object sender, System.EventArgs e)
{
// prints the value of the first cell in the DataGrid
Label2.Text += myDataGrid.SelectedItem.Cells[0].Text;
}

This method is pretty simple. When the datagrid select link button is pressed. We retrieve the item from the datagrid which is residing on the same row on which the link button is pressed. As we can see above in the code that we are retrieving the value from the first column of the datagrid.

I hope you all liked the article happy programming !

Download Sample Code

This is the Header




This is the footer




« « MSAS : Office 2000 OLAP Components
Oracle 9i Database Triggers » »

Author Description

Avatar

Editorial Team at Exforsys is a team of IT Consulting and Training team led by Chandra Vennapoosa.

Free Training

RSSSubscribe 394 Followers
  • Popular
  • Recent
  • Creating and consuming XML Web Services with C#

    April 14, 2005 - 0 Comment
  • ASP .NET Migration and Interoperability

    April 24, 2005 - 0 Comment
  • Managing State with ASP.NET and C#

    May 3, 2005 - 0 Comment
  • ASP.NET with C# Training Launch

    February 19, 2005 - 0 Comment
  • Caching in ASP.NET

    May 9, 2005 - 0 Comment
  • Introduction to ASP.NET with C#

    February 20, 2005 - 0 Comment
  • Configuring and Deploying ASP.NET Applications

    May 14, 2005 - 0 Comment
  • ASP.NET with C# Training Course Outline

    February 19, 2005 - 0 Comment
  • Securing ASP.NET Applications with C#

    May 14, 2005 - 0 Comment
  • ASP.NET Web Forms Controls

    February 26, 2005 - 0 Comment
  • Securing ASP.NET Applications with C#

    May 14, 2005 - 0 Comment
  • Configuring and Deploying ASP.NET Applications

    May 14, 2005 - 0 Comment
  • Caching in ASP.NET

    May 9, 2005 - 0 Comment
  • Managing State with ASP.NET and C#

    May 3, 2005 - 0 Comment
  • ASP .NET Migration and Interoperability

    April 24, 2005 - 0 Comment
  • Creating and consuming XML Web Services with C#

    April 14, 2005 - 0 Comment
  • Managing Data with ADO.NET DataSets and C#

    April 8, 2005 - 0 Comment
  • Accessing Data with C#

    March 19, 2005 - 0 Comment
  • Using Rich Server Controls with C#

    March 12, 2005 - 0 Comment
  • ASP .NET: Validating User Input with C#

    March 4, 2005 - 0 Comment

Exforsys e-Newsletter

ebook
 

Related Articles

  • Securing ASP.NET Applications with C#
  • Configuring and Deploying ASP.NET Applications
  • Caching in ASP.NET
  • Managing State with ASP.NET and C#
  • ASP .NET Migration and Interoperability

Latest Articles

  • Project Management Techniques
  • Product Development Best Practices
  • Importance of Quality Data Management
  • How to Maximize Quality Assurance
  • Utilizing Effective Quality Assurance Strategies
  • Sitemap
  • Privacy Policy
  • DMCA
  • Trademark Information
  • Contact Us
© 2023. All Rights Reserved.IT Training and Consulting
This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish.AcceptReject Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT