在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;
}
}
