我有gridview
显示来自sql
表的大量行。我还在checkbox
标头中有chkboxSelectAll
gridview
来检查gridview
中的所有行。
chkboxSelectAll
oncheckedchange
的代码:
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grid.HeaderRow.FindControl("chkboxSelectAll");
foreach (GridViewRow row in Grid.Rows)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
}
if (ChkBoxHeader.Checked == false)
{
ChkBoxRows.Checked = false;
}
}
}
但是,我只想检查标题复选框后检查前5行gridview。
我搜索的所有答案都是针对数据表或数据集但没有针对gridview本身。
有没有办法做到这一点。任何帮助将不胜感激.. !!
答案 0 :(得分:4)
如果第二条评论的答案为真,那么这将是您的解决方案(例如):
protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
{
CheckBox ChkBoxHeader = (CheckBox)Grid.HeaderRow.FindControl("chkboxSelectAll");
bool sign = ChkBoxHeader.Checked == true;
int counter = 0;
foreach (GridViewRow row in Grid.Rows)
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow");
ChkBoxRows.Checked = sign;
counter++;
if (counter == 5)
{
break;
}
}
}
答案 1 :(得分:1)
您可以使用LINQ来执行此操作:
foreach (GridViewRow row in Grid.Rows.Take(5))
{
CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow");
if (ChkBoxHeader.Checked == true)
{
ChkBoxRows.Checked = true;
}
if (ChkBoxHeader.Checked == false)
{
ChkBoxRows.Checked = false;
}
}