/* ------------------------ My Meta Content Here SEO ------------------------ */

Pages

Main Menu

Friday, May 23, 2014

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

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:


   
       
           
               
                   
               
           
       
   


and then use

    string columnValue = ((Label)e.Row.FindControl("lblName")).Text;

No comments:

Post a Comment

My Blog List

  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी संतान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    2 months ago
  • काश - काश मुझे भी पीने की आदत होती,मैं कब का मुर्दा हो गया होता। छुटकारा मिलता आज के आतंकवाद से, किसी शमशान भूमि में सो गया होता। मेरा एतबार कौन करेगा, मैंने मुर...
    2 months ago
  • Kumaon University Nainital B.Ed entrance exam test result 2012 - कुमाऊँ विश्वविधालय, नैनीताल (उत्तराखण्ड)
    10 years ago