简体   繁体   中英

ASP GridView select row by index

I got GridView element. I highlight selected row with some color. But the problem is when I select new element the elements which were selected before are still highlighted. Here the method and stuff

cs

protected void CompanyGV_SelectedIndexChanged(object sender, EventArgs e)
{

    // CompanyGV.BackColor = System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
    GridViewRow row = CompanyGV.SelectedRow;
    row.BackColor = System.Drawing.ColorTranslator.FromHtml("#BCED91");                   
}

aspx

<asp:GridView ForeColor="Black"  Height="400px" ID="CompanyGV" ShowHeaderWhenEmpty="true"  runat="server" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="companies_id" DataSourceID="SqlDataCompanyList" OnSelectedIndexChanged="CompanyGV_SelectedIndexChanged"> 

                             <Columns>

                                 <asp:CommandField ButtonType="Button" SelectText="Select" ShowSelectButton="True" />

                                <asp:BoundField HeaderText="№" DataField="companies_id" InsertVisible="False" ReadOnly="True" SortExpression="companies_id"/>
                                <asp:BoundField DataField="companies_name" HeaderText="Company" SortExpression="companies_name" />
                            </Columns>

</asp:GridView>

I want to restrict multiple selection and I want to highlight selected element only! IS there are methods to chagne color for whole GridView ? Or is there are way to select row by index and go through rows?

I tried to write smth like this but I getting stack overflow error message

 for (int i = 0; i <= CompanyGV.Rows.Count - 1; i++)
 {

      CompanyGV.SelectRow(i);
      CompanyGV.SelectedRow.Cells[i].BackColor =System.Drawing.ColorTranslator.FromHtml("#FFFFFF");
}

I prefer it at client side. Try this code

JQuery

<script src="~/Content/jquery-ui-1.10.4.custom.js"></script>

<script type="text/javascript">
    $(function() {
        $('#CompanyGV tr').click(function () {
            $('#<%=CompanyGV.ClientID%> tr').removeClass("selected");
            $(this).addClass("selected");
        });
    });
</script>

CSS

.selected{
  background-color:Green !important;
}  

in design view, go to grid views common tasks, then click Edit columns, then use command field node to select Select column a screenshot is here:

Image

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