Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting value from a cell from a gridview on RowDataBound event

string percentage = e.Row.Cells[7].Text; 

I am trying to do some dynamic stuff with my GridView, so I have wired up some code to the RowDataBound event. I am trying to get the value from a particular cell, which is a TemplateField. But the code above always seems to be returning an empty string.

Any ideas?

To clarify, here is a bit the offending cell:

<asp:TemplateField HeaderText="# Percentage click throughs"> <ItemTemplate>     <%# AddPercentClickThroughs((int)Eval("EmailSummary.pLinksClicked"), (int)Eval("NumberOfSends")) %> </ItemTemplate> </asp:TemplateField> 

On a related note, does anyone know if there is a better way of selecting the cell in the row. It sucks putting in cell[1]. Couldn't I do cell["mycellname"], so if I decide to change the order of my cells, bugs wont appear?

like image 342
Chris James Avatar asked Sep 23 '08 15:09

Chris James


People also ask

How to get cell value of GridView in asp net on RowDataBound?

Get cell value of GridView in RowCommand event in ASP.Net The row index can be easily determined using the CommandArgument property of GridViewCommandEventArgs object and using the row index, the GridView Row is referenced. Finally using the reference of the GridView Row, the values from the cells are fetched.

How to get GridView Row value in RowCommand event?

int index = Convert. ToInt32(e. CommandArgument); GridViewRow row = gvCurrentBanners. Rows[index];

How do I get GridView data in RowCommand event?

You can get the data on gridview_RowCommand event by placing below code: Int32 HistoryId = Convert. ToInt32(e. Row.


2 Answers

why not pull the data directly out of the data source.

DataBinder.Eval(e.Row.DataItem, "ColumnName") 
like image 79
Stephen Wrighton Avatar answered Oct 13 '22 00:10

Stephen Wrighton


When you use a TemplateField and bind literal text to it like you are doing, asp.net will actually insert a control FOR YOU! It gets put into a DataBoundLiteralControl. You can see this if you look in the debugger near your line of code that is getting the empty text.

So, to access the information without changing your template to use a control, you would cast like this:

string percentage = ((DataBoundLiteralControl)e.Row.Cells[7].Controls[0]).Text; 

That will get you your text!

like image 36
Chris Avatar answered Oct 13 '22 00:10

Chris