GridView 遍历每一行,两种写法 [转]
方法一:
for (i = 0; i < GridViewID.Rows.Count; i++)
{
CheckBox chkVote = (CheckBox)GridView1.Rows[i].FindControl("CheckBox2");
}
例如:
int intCount = this.GridViewID.Rows.Count; //总行数
int rowsEffected = 0;
for (int i = 0; i < intCount; i++)
{ //在GridView中添加TextBox模版列并取输入的值
TextBox tbMark = this.GridViewID.Rows[i].Cells[2].FindControl("TextBox") as TextBox;
CheckBox CheckSingle = this.GridViewID.Rows[i].Cells[3].FindControl("CheckSingle") as CheckBox;
if (CheckSingle.Checked)
{
paper entity = new paper();
paper paper_op = new paper_op();
entity.question_id = long.Parse(this.GridViewID.DataKeys[i].Value.ToString());
entity.paper_id = long.Parse(Request.QueryString["paperid"].ToString().Trim());
try
{
// entity.point = Convert.ToInt32(tbMark.Text);
string point = tbMark.Text.ToString();
if (point == "")
{
Tools.MSBox("不能为空", String.Format("目标.aspx?id={0}", Request.QueryString["id"]));
}
else
{
entity.point = Convert.ToInt32(point);
}
}
catch (Exception)
{
Tools.MSBox("请输入正确的分数值");
}
int result =paper_add(entity);
if (wwdresult == 1)
{
rowsEffected++; //循环
}
}
if (rowsEffected > 0)
{
Tools.MSBox("插入成功", String.Format("目标.aspx?id={0}", Request.QueryString["id"]));
}
else
{
Tools.MSBox("没有选择!", String.Format("目标.aspx?id={0}", Request.QueryString["id"]));
}
方法二:
foreach (GridViewRow row in GridViewID.Rows)
{
CheckBox chkVote = (CheckBox)row.FindControl("chkVote");
}
两种方法没有太大差别,但是如果你不知道GridViewRow这个类型就很难想到使用这种方法。类似的DataList。
foreach (DataListItem dlItem in this.DataListID.Items)
{
CheckBox chkVote = (CheckBox)dlItem.FindControl("chkVote");
}
在GridView中有一列允许编辑,等它处于编辑状态时是一个TextBox。怎么得到这个TextBox呢?一般我们得到GridView中的控件的方法是在RowDataBound事件中写这行代码((TextBox)e.Row.Cells[8].FindControl("txtFZRQ"));如果用这个方法得到编辑状态下的TextBox时还会出现这个错误:未将对象引用设置到对象的实例。利用下面的方法就可以了。
if ((e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
{
((TextBox)e.Row.Cells[8].FindControl("txtFZRQ"));
}
----------------------------------------------------------------------------------------------------
转自:http://www.cnblogs.com/aito/archive/2008/08/25/1275723.html
----------------------------------------------------------------------------------------------------