简体   繁体   中英

GridView: OnRowDatabound HeaderText Equals to ColumnText with AutoGenerateColumn True c# Asp.net

I have a gridview with first columns is same as headers ie same value with autogeneratecolumns as true, what i need to do in RowDatabound if HeaderText Equals to Intersect of the first Column text, Change the color to Yellow. Please see the attached image of the Desireed Gridview Output.

GridViewDesiredOutput

HTML

 <asp:GridView ID="GvSamples" OnRowDataBound="GvSamples_RowDataBound" runat="server"  AutoGenerateColumns="True">

C#

 public void BindSamplesGrid()
    {
        DataTable _dt = new DataTable();
        _dt = BL.GetSample(_conn);
        GvSamples.DataSource = _dt;
        GvSamples.DataBind();
    }


protected void GvSamples_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            for (int i = 0; i < e.Row.Cells.Count; i++)
            {
                if (e.Row.Cells[i].Text == e.Row.Cells[i].Text)
                e.Row.Cells[i].Text = e.Row.Cells[i].Text.Replace("_", " ");
            }
        }
    }

I am using asp.net C# Gridview.

Thank you

There are a couple of issues with your code. First of all you can only access the header row in DataControlRowType.Header , so coloring the cells as desired must be done in DataControlRowType.DataRow .

Next you are evaluating exactly the same value, so it will always be true: e.Row.Cells[i].Text == e.Row.Cells[i].Text , although this does not seem to do much except replace a _ , which has nothing to do with getting the cell color to be yellow.

The below snippet does what you need. It gets the current row number and colors the correct cell yellow.

protected void GvSamples_RowDataBound(object sender, GridViewRowEventArgs e)
{
    //check if the row is a datarow
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //get the current row number
        int rowIndex = e.Row.RowIndex;

        //check if the rownumber does not exceed the column count
        if (rowIndex < e.Row.Cells.Count - 1)
        {
            //make the cell yellow
            e.Row.Cells[rowIndex + 1].BackColor = Color.Yellow;
        }
    }
}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM