Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the cell value by column name not by index in GridView in asp.net

I am having a gridview in asp.net and now I want the cell value by the column name but not by the cell index.

How would be it possible by retrieving the cell value by the cell column name

like image 333
Vara Prasad.M Avatar asked Mar 15 '12 08:03

Vara Prasad.M


People also ask

How to get Row index by cell value of GridView in c#?

If you want to select the row by row index u can do it as, int rowIndex = 0; dataGridView1. Rows[ rowIndex ];

How do you sort data in GridView by clicking column header?

Start by adding a GridView to your web page. To make the columns sortable, you need to set the GridView's property AllowSorting = “true” and OnSorting = “OnSorting”. SortExpression property will hold the name of the column you want to sort.

What is sort expression in GridView?

By default, the GridView control sorts a single column at a time. The sort expression simply contains the name of the field to sort. You can also sort multiple columns at a time by programmatically setting this property to a comma-separated list of field names.


1 Answers

GridView does not act as column names, as that's it's datasource property to know those things.

If you still need to know the index given a column name, then you can create a helper method to do this as the gridview Header normally contains this information.

int GetColumnIndexByName(GridViewRow row, string columnName) {     int columnIndex = 0;     foreach (DataControlFieldCell cell in row.Cells)     {         if (cell.ContainingField is BoundField)             if (((BoundField)cell.ContainingField).DataField.Equals(columnName))                 break;         columnIndex++; // keep adding 1 while we don't have the correct name     }     return columnIndex; } 

remember that the code above will use a BoundField... then use it like:

protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e) {     if (e.Row.RowType == DataControlRowType.DataRow)     {         int index = GetColumnIndexByName(e.Row, "myDataField");         string columnValue = e.Row.Cells[index].Text;     } } 

I would strongly suggest that you use the TemplateField to have your own controls, then it's easier to grab those controls like:

<asp:GridView ID="gv" runat="server">     <Columns>         <asp:TemplateField>             <ItemTemplate>                 <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />             </ItemTemplate>         </asp:TemplateField>     </Columns> </asp:GridView> 

and then use

string columnValue = ((Label)e.Row.FindControl("lblName")).Text; 
like image 113
balexandre Avatar answered Sep 20 '22 11:09

balexandre