C# 更改asp.net gridview中选定行的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17269411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:59:48  来源:igfitidea点击:

Changing color of selected row in asp.net gridview

c#asp.netgridviewwebforms

提问by Vishweshwar Kapse

Hi i am trying to change the color of the selected row in the asp.net gridview i have defined my grid view like this

嗨,我正在尝试更改 asp.net gridview 中所选行的颜色,我已经这样定义了我的网格视图

<asp:GridView ID="gridContractor" runat="server" AllowPaging="True" AllowSorting="True"
                AutoGenerateColumns="False" CssClass="GridViewStyle" GridLines="None" EnableModelValidation="True"
                DataKeyNames="DeviceID" OnRowCommand="gridContractor_RowCommand" OnPageIndexChanging="gridContractor_PageIndexChanging"
                Width="100%" EmptyDataText = "No records to display" EmptyDataRowStyle-HorizontalAlign="Center">
                <AlternatingRowStyle BackColor="White" />
                <Columns>
                    <asp:BoundField HeaderText="Device IMEI" DataField="DeviceID" Visible="false">
                        <HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Width="175" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="Person Name" DataField="PersonName">
                        <HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="#Observations" DataField="GpsPointsCount" ControlStyle-Width="50px">
                        <HeaderStyle HorizontalAlign="Right" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" Width="50" />
                    </asp:BoundField>
                    <asp:BoundField HeaderText="#Violations" DataField="ViolationCount" ControlStyle-Width="60px">
                        <HeaderStyle HorizontalAlign="Right" VerticalAlign="Middle" />
                        <ItemStyle HorizontalAlign="Right" VerticalAlign="Middle" Width="60" />
                    </asp:BoundField>
                    <asp:TemplateField HeaderText="" ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="50">
                        <ItemTemplate>
                            <asp:Button ID="btnEdit" runat="server" Text="View" CommandName="View" Enabled="true" OnClick="btn_GrdClick"
                                CommandArgument="<%#Bind('DeviceID') %>" />
                        </ItemTemplate>
                        <HeaderStyle Width="50" />
                        <ItemStyle HorizontalAlign="Center"></ItemStyle>
                    </asp:TemplateField>
                </Columns>
                <RowStyle CssClass="RowStyle" />
                <EmptyDataRowStyle CssClass="EmptyRowStyle" />
                <PagerStyle CssClass="PagerStyle" />
                <SelectedRowStyle BackColor="AliceBlue" />
                <HeaderStyle CssClass="HeaderStyle" />
                <EditRowStyle CssClass="EditRowStyle" />
                <AlternatingRowStyle CssClass="AltRowStyle" />
            </asp:GridView>

and i have handled the button click event the problem is that each time i am selecting a row the previous row color is not getting changed even though i am doing it. once clicked the row remains yellow can somebody help me please

并且我已经处理了按钮单击事件,问题是每次我选择一行时,即使我正在这样做,前一行的颜色也不会改变。单击后,该行仍然是黄色的,有人可以帮我吗

my aspx.cs code

我的 aspx.cs 代码

 protected void btn_GrdClick(object sender, EventArgs e)
    {
        GridViewRow PreviousRow = Session["PreviousRow"] as GridViewRow;
        if (PreviousRow != null)
            PreviousRow.ForeColor = Color.White;
        GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
        row.ForeColor = Color.Yellow;
        Session["PreviousRow"] = row;
    }

采纳答案by nunespascal

GridViewRowis a control. Like every object on the page, it will be created during the page life cycle.
The reference you hold in Sessionis to the object created during the last request.

GridViewRow是一个控件。与页面上的每个对象一样,它将在页面生命周期中创建。
您持有的引用Session是对上次请求期间创建的对象。

To solve the problem, keep only the index(or key) of the row in Sessionand use that to change the color of previous row.

要解决此问题,请仅保留行的索引(或键)Session并使用它来更改前一行的颜色。

protected void btn_GrdClick(object sender, EventArgs e)
{
    if(Session["PreviousRowIndex"] != null)
    {
      var previousRowIndex = (int)Session["PreviousRowIndex"];
      GridViewRow PreviousRow = MyGridView.Rows[previousRowIndex];
      PreviousRow.ForeColor = Color.White;
    }

    GridViewRow row = (GridViewRow)((Button)sender).NamingContainer;
    row.ForeColor = Color.Yellow;
    Session["PreviousRowIndex"] = row.RowIndex;
}

回答by Jalpesh Vadgama

try something like below.

尝试如下。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes.Add("onmouseover", "this.style.cursor='hand';this.style.backgroundColor='yellow'");
        e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='white'");
    }
}

回答by bazz

1) First thing you need to do is to handle the Grid's RowCommand event, protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e). What you are doing is treating button's click event separate to the gridview's command event. 2) you can assign an index to the command argument, and change the row's colour and set all the other rows to the default colour. One example can be found here

1)您需要做的第一件事是处理Grid的RowCommand事件,protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)。您正在做的是将按钮的单击事件与 gridview 的命令事件分开处理。2)您可以为命令参数分配一个索引,并更改行的颜色并将所有其他行设置为默认颜色。一个例子可以在这里找到

Hope this helps,

希望这可以帮助,

回答by Hiren

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
    GridView1.SelectedRow.BackColor = System.Drawing.Color.White;
}

回答by Hiren

Use GridView Load Event

使用 GridView 加载事件

I have given example of my code,

我已经给出了我的代码示例,

Protected Sub grvaddbook_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles grvaddbook.Load
    Dim row1 As GridViewRow
    row1 = grvaddbook.HeaderRow
    Dim i As Integer
    i = 0
    For Each row As GridViewRow In grvaddbook.Rows
        Dim main As Label = DirectCast(grvaddbook.Rows(i).Cells(0).FindControl("lblismain"), Label)

        If main.Text = 1 Then
            Dim lbtnmakedefault As LinkButton = DirectCast(grvaddbook.Rows(i).Cells(0).FindControl("lbtnmakedefault"), LinkButton)
            lbtnmakedefault.Visible = False
            mainaid = DirectCast(grvaddbook.Rows(i).Cells(0).FindControl("lblaid"), Label).Text
        End If
        i = i + 1
    Next
End Sub

回答by Atters

I was looking for a solution to this problem and then saw a couple of threads like this mentioning that you need to track the selected row in the session. Whilst this may be true for a full postback when it's partial I found a better solution using Css.

我一直在寻找这个问题的解决方案,然后看到几个像这样的线程提到您需要跟踪会话中的选定行。虽然这对于部分回发可能是正确的,但我找到了使用 Css 的更好解决方案。

Gridview is in an update panel, the surrounding div has a class=grid and the gridview has class=datatable then the following elements are defined within the Gridview;

Gridview 在更新面板中,周围的 div 有一个 class=grid 并且 gridview 有 class=datatable 然后在 Gridview 中定义了以下元素;

RowStyle CssClass="item-row"

RowStyle CssClass="item-row"

SelectedRowStyle CssClass="selectedItem-row"

SelectedRowStyle CssClass="selectedItem-row"

Then the associated css looks like this;

然后关联的css看起来像这样;

    .grid .datatable .item-row TD {
        border-bottom: #bbd9ee 1px solid;
        text-align: left;
        padding-bottom: 6px;
        padding-left: 4px;
        padding-right: 4px;
        font-size: 0.7em;
        border-top: #bbd9ee 1px solid;
        padding-top: 6px;
    }

        .grid .datatable .item-row TD.highlightcell {
            background-color: #fffacd;
            color: #000;
        }

    .grid .datatable .item-row:hover {
        background-color: #fffacd;
        color: #000;
    }

    .grid .datatable .selectedItem-row TD {
        border-bottom: #bbd9ee 1px solid;
        text-align: left;
        padding-bottom: 6px;
        padding-left: 4px;
        padding-right: 4px;
        font-size: 0.7em;
        border-top: #bbd9ee 1px solid;
        padding-top: 6px;
        background-color: #d7ffcd;
    }