GridView中CheckBox单击事件(oncheckedchanged)

在GridView中加入 CheckBox控件,想通过单击选中出现如下图所示效果:

具体做法是:

前台GV部份省掉。只加关键的CheckBox部份。

view plaincopy to clipboardprint?
<asp:CheckBox ID="ItemCheckBox" oncheckedchanged="ItemCheckBox_CheckedChanged" AutoPostBack="true" runat="server" /> 
<asp:CheckBox ID="ItemCheckBox" oncheckedchanged="ItemCheckBox_CheckedChanged" AutoPostBack="true" runat="server" />

此代码需要注意的是:

AutoPostBack="true"

此句的效果是选中后才会执行后台的代码。

后台代码:C#

view plaincopy to clipboardprint?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
//单独选中   
    protected void ItemCheckBox_CheckedChanged(object sender, EventArgs e)   
    {   
        CheckBox chk =(CheckBox)sender;   

        //以下两句为 选中背景色       第一种方法通过 Parent 获得GridViewRow   
        DataControlFieldCell dcf = (DataControlFieldCell)chk.Parent;    //这个对象的父类为cell   
        GridViewRow gr = (GridViewRow)dcf.Parent;                   //cell的父类就是row,这样就得到了该checkbox所在的该行   

        //另外一种NamingContainer获得 GridViewRow   
        int index = ((GridViewRow)(chk.NamingContainer)).RowIndex;    //通过NamingContainer可以获取当前checkbox所在容器对象,即gridviewrow   

        string strsql="";   
        string qtable = GVOpen.Rows[index].Cells[4].Text.Trim();   
        string qid = GVOpen.Rows[index].Cells[1].Text.Trim();   
           

        if (chk.Checked)   
        {   
            gr.BackColor = System.Drawing.Color.Green;   
                    }   
        else 
        {   
            gr.BackColor = GVOpen.RowStyle.BackColor;   
        }   
    }

原文地址:https://www.cnblogs.com/yubufan/p/7385308.html