Click here to Skip to main content
Licence CPOL
First Posted 21 Jan 2010
Views 11,500
Bookmarked 12 times

Extracting Values from a Gridview

By | 21 Jan 2010 | Article
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:

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:

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)

About the Author

SachinKumarK

Web Developer

India India

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralHi PinmemberKalyani Kailasamoni4:51 28 May '10  
GeneralRe: Hi PinmemberSachinKumarK5:09 28 May '10  
GeneralMy vote of 1 PinmemberJohn_Crocker21:55 21 Jan '10  
GeneralHi PinmemberAnil Srivastava18:55 21 Jan '10  
GeneralMy vote of 1 PinmvpSacha Barber11:21 21 Jan '10  
Generalgood job PinmemberArlen Navasartian9:37 21 Jan '10  

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

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

Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 21 Jan 2010
Article Copyright 2010 by SachinKumarK
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid