ASP Gridview: Collect cell value from header column text?

I am working with some gridviews in asp What I want to find out is this: Is there a fast/good way to grab the correct cells based on header column text?

So far I have not found exactly what I want looking around.

What I am looking for is something more like: row.Cells["Name_of_Column"].Text;

There is a method to iterate over every column and then if the label is matching grab the text see: How to get column name from gridview?

However, what I am doing is making a gridview with the columns selected by the user programatically so I am not sure if row.Cells[2].Text will be the right value or if it could be row.Cells[3].Text or row.Cells[13].Text etc.

Once again I can solve this with a loop I am looking for a less messy more elegant solution.

Thanks in advance I will try to upvote good answers.


For what it's worth, you can use LINQ (which also uses loops) to create a dictionary with the name of the column as key and it's index as value:

Dictionary<string, int> colLookup = GridView1.Columns.Cast<DataControlField>()
    .Select((Col, Index) => new { Col.HeaderText, Index })
    .ToDictionary(f => f.HeaderText, f => f.Index);
string cellText = e.Row.Cells[colLookup["Name_of_Column"]].Text;

You could make it an instance field which you initalize once(f.e. in Page_Load), then you can reuse it where you need it.

try this,

for (int i = 0; i < grdToDisplay.Columns.Count; i++)
  string header = grdToDisplay.Columns[i].HeaderText;

Need Your Help

add stroke to text (outline) with Coldfusion and Java (classes/methods)

java coldfusion coldfusion-10

I've been trying to add stroke to text using Coldfusion code and Java classes / methods. I found some pointers on Leigh's old blog (cfsearching) and have been spending a lot of my free time reading...

Lotus Domino: vertical scroll bar for view on web

view scrollbar lotus-domino

There is a frameset which contains 2 frames: 1st frame contains an oultine and the 2nd frame contains a view.