Link to home
Start Free TrialLog in
Avatar of portalvale
portalvale

asked on

Get value of e.Row.Cells[2] and write to Label1

Please help me solve this... I want to get data from e.Row.Cells[2] and send value to Label1 on .aspx see below... Thank you!


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            string CellValue = (e.Row.Cells[1].Text);
            string CellValue2 = (e.Row.Cells[0].Text);


            if (CellValue2 == "BMW")
 ------->>>>>               Label1.Text = "value of e.Row.Cell[2]";   <<<<<------ How do I write this?
               
            else if (CellValue == "FORD")
                e.Row.BackColor = System.Drawing.Color.Green;
            e

   
            }

        }
    }
Avatar of Nash2334
Nash2334

To get the value of the cell the easiest thing to do would be to use an ItemTemplate in the Gridview with a Label, then find the Label using the FindControl method in the RowDataBound method.
Example:

Your GridView:

                   <asp:TemplateField HeaderText="MyHeader">
                        <ItemTemplate>
                            <asp:Label ID="MyLabel" runat="server"></asp:Label>
                        </ItemTemplate>
                    </asp:TemplateField>

In your RowDataBoundMethod:

Label myLabel = (Label)e.Row.FindControl("MyLabel"); // ID of the control you are seeking

if (myLabel != null)
    Label1.Text  = myLabel.Text;
ASKER CERTIFIED SOLUTION
Avatar of Nathan Bove
Nathan Bove
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That's a good point nbove, but I tend to avoid using ordinals when referencing objects.  What happens if the template is modified and a column is added before the 3rd column?  The RowBound is suddenly referencing the wrong column, unless the code in that method is modified as well.

By using a Label and FindControl, you don't have to worry about column orders.  Whether the Label is in column 0 or column 100, the reference will never change in the RowBound method.
Avatar of portalvale

ASKER

This is all I needed...

Label1.Text = e.Row.Cells[2].Text


Thx