A few days ago a forum question was posted in DevPinoy.org on how to read the values of a inside a GridViewRow and assigning them to a Label control(or TextBox) when that row is selected. I wasn't able to reply to that thread early due to time constraints with a project I had at that time but I told myself that I'm going to answer it as soon as my schedule frees up. This article is a bit late(about 3 days to be exact) but i still hope that this answers that persons question.
Ok, now on with the show.
Basically there are a few ways you could do this depending on what you preffer. There's the "go back to the source of data approach" wherein you back and query the source of data based on a DataKey you specified on the GridView or you could go to the easy route which is reading the TableCell values on the selected row. This is the way i chose to demonstrate my solution.
The first thing to figureout when implementing this solution is whether or not you want to use a CommandField or a TemplateField. A CommandField is a class that enables a GridView control to display a command button that performs select, delete, update, insert operations. On the otherhand a TemplateField allows you to add custom content for each record displayed in a GridView. A TemplateField is necessary whenever you want to add multiple controls inside one TableCell.
My sample for this article implements both approch so that you could see whats the dirrence between the two implementations.
Lets stat with the CommandField example. To use this class on your Gridview you need to add a CommandField column to your GridView with the ShowSelectButton property set to true. This option displays a LinkButton that acts as the select action for your GridView.
<asp:GridView ID="peopleGridView" runat="server" AutoGenerateColumns="False" DataKeyNames="PersonID" OnSelectedIndexChanging="peopleGridView_SelectedIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Select" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="Age" HeaderText="Age" />
</Columns>
</asp:GridView>
I then hooked a function to the OnSelectedIndexChanging event called peopleGridView_SelectedIndexChanging so that a function is called whenever a new selection occurs. Below is the code listing for this method
protected void peopleGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//get our new selected index
int rowIndex = e.NewSelectedIndex;
//assign the row number to our message label
messageLabel.Text = String.Format("{0}", rowIndex + 1);
//display the value on column 1 of the selected row
nameLabel.Text = peopleGridView.Rows[rowIndex].Cells[1].Text;
//display the value on column 2 of the selected row
emailLabel.Text = peopleGridView.Rows[rowIndex].Cells[2].Text;
//display the value on column 3 of the selected row
ageLabel.Text = peopleGridView.Rows[rowIndex].Cells[3].Text;
}
What happens on this code is that this method is called whenever our CommandField button is clicked. The first thing that we did was get the rowIndex of new selected row then pulling the values on the TableCells for that specific row based on several predetermined indices and then assigning those values to our Label. Pretty simple huh?
Now lets see how our GridView looks like on our TemplateField implementation.
<asp:GridView ID="peopleGridView" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="selectButton" runat="server" Text="Select" OnClick="selectButton_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="Age" HeaderText="Age" />
</Columns>
</asp:GridView>
The first thing that you would notice is that the GridView doesn't have the OnSelectedIndexChanging event hooked to any function. The reason behind this is because we are not triggering the event of the GridView but instead we are calling the OnClick event of our LinkButton inside out TemplateField. The LinkButton os hooked to function called selectButton_Click that has the following implementation:
protected void selectButton_Click(object sender, EventArgs e)
{
LinkButton selectButton = (LinkButton)sender;
//the button is contained in a TableCell which is contained in a GridViewRow
GridViewRow row = (GridViewRow)selectButton.Parent.Parent;
//get the row index of the selected row
int rowIndex = row.RowIndex;
//assign the row number to our message label
messageLabel.Text = String.Format("{0}", rowIndex + 1);
//display the value on column 1 of the selected row
nameLabel.Text = peopleGridView.Rows[rowIndex].Cells[1].Text;
//display the value on column 2 of the selected row
emailLabel.Text = peopleGridView.Rows[rowIndex].Cells[2].Text;
//display the value on column 3 of the selected row
ageLabel.Text = peopleGridView.Rows[rowIndex].Cells[3].Text;
}
A noticeable code on the listing above is the fact that we are reading the rowIndex based on what row contains the LinkButton that triggered the event. The next few code below of that line is similar to our CommandField example which states that we are reading the values on each column on that row.
And that's it. That's the way to read values from your GridViewRow based on a selected row. Below is complete code listing of the slightly refactored version of the codes above combined into one sample:
[default.aspx]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_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>How To: Read the values of a GridViewRow and assign them to a control</title>
</head>
<body>
<form id="form1" runat="server">
<div>
You have clicked:
<asp:Label ID="messageLabel" runat="server"></asp:Label><br />
Name:
<asp:Label ID="nameLabel" runat="server"></asp:Label><br />
Email:
<asp:Label ID="emailLabel" runat="server"></asp:Label><br />
Age:
<asp:Label ID="ageLabel" runat="server"></asp:Label><br />
<asp:GridView ID="peopleGridView"
runat="server"
AutoGenerateColumns="False"
OnSelectedIndexChanging="peopleGridView_SelectedIndexChanging">
<Columns>
<asp:CommandField ShowSelectButton="True" SelectText="Select by CommandField" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="selectButton"
runat="server"
Text="Select By TemplateField"
OnClick="selectButton_Click">
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Email" HeaderText="Email" />
<asp:BoundField DataField="Age" HeaderText="Age" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
[default.aspx.cs]
using System;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Web.UI;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
public void BindData()
{
peopleGridView.DataSource = GetPersonList();
peopleGridView.DataBind();
}
protected void selectButton_Click(object sender, EventArgs e)
{
LinkButton selectButton = (LinkButton)sender;
//the button is contained in a TableCell which is contained in a GridViewRow
GridViewRow row = (GridViewRow)selectButton.Parent.Parent;
//get the row index of the selected row
int rowIndex = row.RowIndex;
//call our populate function
PopulateLabelsByRowIndex(rowIndex);
}
protected void peopleGridView_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
//get our new selected index
int rowIndex = e.NewSelectedIndex;
//call our populate function
PopulateLabelsByRowIndex(rowIndex);
}
private void PopulateLabelsByRowIndex(int rowIndex)
{
//assign the row number to our message label
messageLabel.Text = String.Format("{0}", rowIndex + 1);
//display the value on column 2 of the selected row
nameLabel.Text = peopleGridView.Rows[rowIndex].Cells[2].Text;
//display the value on column 3 of the selected row
emailLabel.Text = peopleGridView.Rows[rowIndex].Cells[3].Text;
//display the value on column 4 of the selected row
ageLabel.Text = peopleGridView.Rows[rowIndex].Cells[4].Text;
}
public List<Person> GetPersonList()
{
//create a new list of person
List<Person> people = new List<Person>();
// add some dummy records to our list
people.Add(new Person(1, "Keith Rull", "keith@devpinoy.org", 25));
people.Add(new Person(2, "Charissa Rull", "cha@devpinoy.org", 23));
people.Add(new Person(3, "Ivy Rull", "ivy@devpinoy.org", 24));
people.Add(new Person(4, "Orlando Rull", "orlando@devpinoy.org", 52));
people.Add(new Person(5, "Benilda Rull", "benilda@devpinoy.org", 49));
people.Add(new Person(6, "Ria Rull", "ria@devpinoy.org", 22));
people.Add(new Person(7, "Renz Rull", "renz@devpinoy.org", 20));
//return our list
return people;
}
}
public class Person
{
private int _personID;
private string _name;
private string _email;
private int _age;
public int PersonID
{
get
{
return _personID;
}
set
{
_personID = value;
}
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public string Email
{
get
{
return _email;
}
set
{
_email = value;
}
}
public int Age
{
get
{
return _age;
}
set
{
_age = value;
}
}
public Person(int personID, string name, string email, int age)
{
this.PersonID = personID;
this.Name = name;
this.Email = email;
this.Age = age;
}
}
Hope you leaned something from the article today ;) More to come tommorow. Thanks!
Download the code for this tutorial: KeithRull.LinkButtonsAndGridViews.zip (3.1 KB)
Posted
Nov 01 2007, 02:26 PM
by
keithrull