日期:2014-05-17  浏览次数:20495 次

怎样判断GridView中的CheckBox是否被选中?
我的代码如下:
.aspx
<asp:TemplateField     HeaderText= "选择 "   >
                                        <ItemTemplate>
                                                <asp:CheckBox   ID= "chk选择 "   runat= "server "   > </asp:CheckBox>
                                        </ItemTemplate>
                                        <HeaderStyle   HorizontalAlign= "Center "   VerticalAlign= "Middle "   />
                                        <ItemStyle   HorizontalAlign= "Center "   />
                                </asp:TemplateField>

.cs
foreach   (GridViewRow   grvRow   in   grv.Rows)
                {
                        CheckBox   chk   =   (CheckBox)grvRow.FindControl( "chk选择 ");
                        if   (chk.Checked)
                        {
                                Response.Write( " <script   language= 'javascript '> alert( '已选中! '); </script> ");
                        }
                }

可是我选中CheckBox以后仍然没有反应,不知道错在哪里?

------解决方案--------------------
CheckBox chk = (CheckBox)grvRow.Cells[0].FindControl( "chk选择 ");

加入Cells[??],你模板列的索引,第一个为0
------解决方案--------------------
1。
绑定 GridView 放在 !IsPostBack 里面

if(!IsPostBack) {
// 这里绑定
}

2。
CheckBox chk = (CheckBox)grvRow.Cells[0].FindControl( "chk选择 ");

加入Cells[??],你模板列的索引,第一个为0

==========

@webipstin(太多的事不明白)

不要再引用 Cells[ < <cellIndex> > ] ,这是自找麻烦

直接 GridViewRow.FindControl( "MyControlID ");

GridViewRow 和 GridViewRow.Cells[ < <cellIndex> > ] 在同一个 NamingContainer (命名容器)

FindControl 基于当前的 NamingContainer 查找

------解决方案--------------------
代码没什么问题,但是ID好像不能用中文吧