实现Gridview 点击行 选中行的方法 代码不多很实用

首先要在GridView中做一个选择列,隐藏起来

 <asp:TemplateField HeaderStyle-Width="15"  ControlStyle-CssClass="showcell" >  
                <ItemTemplate>              
                    <asp:LinkButton runat="server" ID="btnDetial" CommandName="Detail"  CommandArgument='<%# Eval("ID") %>'>辅助列</asp:LinkButton> 
                </ItemTemplate> 
                    <ControlStyle CssClass="showcell" />
                    <HeaderStyle Width="15px" />
            </asp:TemplateField>

Class 是隐藏的属性 这里不能用 Visible=false

在Js里写一个 Linkbutton 点击事件


 function ClickEvent(cId)    
        {                   
            document.getElementById(cId).click();                     
        }

 然后添加 GridView 的RowDataBound事件

 e.Row.Attributes.Add("onclick", "ClickEvent('" + e.Row.Cells[8].FindControl("btnDetial").ClientID + "')");
 e.Row.Attributes.Add("id", e.Row.Cells[8].FindControl("btnDetial").ClientID+"tr");
 这样 我们点击一行的任意地方都能 触发LinkButton的事件。现在我们来给LinkButton添加事件。

添加Gridview 的RowCommand事件

  if (e.CommandName == "Detail")
            {
                int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
                if (rowIndex != (int)Session["oldrow"])
                {                         
              
                if ((int)Session["oldrow"] != -1)
                {
                    if (GridView1.Rows[(int)Session["oldrow"]].Attributes.CssStyle["background-color"] == "#C5BBAF")
                    {
                        GridView1.Rows[(int)Session["oldrow"]].Attributes.CssStyle["background-color"] = Session["oldcolor"].ToString();
                    }
                }
                if (GridView1.Rows[rowIndex].Attributes.CssStyle["background-color"]==null)
                {
                    Session["oldcolor"] = "";
                }
                else
                {
                    Session["oldcolor"] = GridView1.Rows[rowIndex].Attributes.CssStyle["background-color"];
                }
               
                GridView1.Rows[rowIndex].Attributes.CssStyle["background-color"] = "#C5BBAF";
                Session["oldrow"] = rowIndex;
            }

这样我们完成了90% 还有里面的Session 设置 。

 if (!IsPostBack)
            {
                          
                Session["oldrow"] = -1;
                Session["oldcolor"] = "";
            }
为什么会有这2个Session因为 我的行市交替颜色变换的 所以 要记录一下。

最后 在分页的时候

 protected void GridView1_PageIndexChanged(object sender, EventArgs e)
        {
            Session["oldrow"] = -1;
            Session["oldcolor"] = "";
        }

完成。



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值