Click here to Skip to main content
15,895,084 members
Articles / Web Development / ASP.NET

Extracting Values from a Gridview

Rate me:
Please Sign up or sign in to vote.
2.75/5 (5 votes)
21 Jan 2010CPOL 33.2K   16   6
Extracting Values from a Gridview

Introduction

I have frequently come across the requirement where values from a gridview need to be extracted. The code here is a generic one that extracts the cell values in a given row and returns the collection.

Using the Code

The code is given below:

C#
public IDictionary<string, object> GetValues(GridViewRow row)
{
    IOrderedDictionary dictionary = new OrderedDictionary();

    foreach (Control control in row.Controls)
    {
        DataControlFieldCell cell = control as DataControlFieldCell;

        if ((cell != null) && cell.Visible)
        {
            cell.ContainingField.ExtractValuesFromCell
			(dictionary, cell, row.RowState, true);
        }
    }

    IDictionary<string, object> values = new Dictionary<string, object>();

    foreach (DictionaryEntry de in dictionary)
    {
        values[de.Key.ToString()] = de.Value;
    }

    return values;
} 

The values returned can be accessed in the following way:

C#
GridViewRow row = GridView1.Rows[e.RowIndex];
var m_values = this.GetValues(row);
string userid = m_values["UserID"].ToString();

where the string value is the Column name in the GridView.

The above code might not work properly in case of cells having UserControls. For all other cases whether it be a bound field or template field, the code would work.

History

  • 21st January, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralHi Pin
Kalyani Kailasamoni28-May-10 4:51
Kalyani Kailasamoni28-May-10 4:51 
GeneralRe: Hi Pin
SachinKumarK28-May-10 5:09
SachinKumarK28-May-10 5:09 
GeneralMy vote of 1 Pin
Argyle4Ever21-Jan-10 21:55
Argyle4Ever21-Jan-10 21:55 
GeneralHi Pin
Anil Srivastava21-Jan-10 18:55
Anil Srivastava21-Jan-10 18:55 
First Let me tell what is dictionary then Idictionary. I assume it is interface.
Is it something like key/value pair.
That has implimentation in   all the programming languages.
GeneralMy vote of 1 Pin
Sacha Barber21-Jan-10 11:21
Sacha Barber21-Jan-10 11:21 
Generalgood job Pin
Arlen Navasartian21-Jan-10 9:37
Arlen Navasartian21-Jan-10 9:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.