我需要帮助遍历页面上的两个gridviews。最终,我将在页面上共有6个网格视图(或部分)。每个gridview都有相同的列,但每个列都有不同数量的行。迭代的目标是计算当前gridview迭代中总gridview行中一列中选定的radiobuttonlist项的总数,以便信息可以显示在Submit按钮上的标签上,如下所示: “10检查第1部分中的14个评分。“或 ”检查第2部分中11分的11分。或者任何情况。需要帮助循环浏览一个页面上的多个gridviews c#.net
我用Google搜索拿出我到目前为止的代码,并遵循这一线索,包括聊天How to use a for loop to modify multiple controls (gridview)
但我不明白如何处理这行代码做。省略号后是什么?它适用于我的情况吗?
((GridView) Page.FindControl("GridView" + i)).Rows[1].........
当我添加了.Rows[j]
(或1),出现在.Rows
一个红色的波浪线...有警告:system.web.ui.control不包含定义“行”并没有extenstion方法“行'接受类型system.web.ui.control的第一个参数可以找到(你是否缺少using指令或程序集引用?)。我确实有using System.Linq
;声明在我的页面顶部。 这是我的代码,通过gridviews计数。 GridView id是GridView1,GridView2等.GridViews使用sqldatasource填充并包含绑定和模板字段列。如果我通过查看在浏览器中运行的代码它抛出错误“对象引用不设置到对象的实例”在这行代码:
foreach (GridViewRow row in gv.Rows);
在调试不过,它似乎认识到正确的GridView因为它获得了正确的行数并选择了正确的单选按钮项目。
代码:
//UPDATED code includes solution:
protected void CountSelectedRatings()
{
int count = 0;
int itemsSelected = 0;
string str = string.Empty;
int i = 1;
//loop through 6 gridviews
for (i = 1; i <= 6; i++)
{
//identify current grid to iterate through
GridView gv = (GridView)Page.FindControl("GridView" + i);
itemsSelected = 0;
if (gv != null)
{
foreach (GridViewRow row in gv.Rows)
{
count = gv.Rows.Count;
RadioButtonList rbl = row.FindControl("rblRating" + i) as RadioButtonList;
foreach (ListItem item in rbl.Items)
{
if (item.Selected == true)
{
//increment count
itemsSelected += 1;
switch (i)
{
case 1:
strRowCountMessage1 = itemsSelected + " of " + count + " ratings in Section " + i + " are checked.";
lblRowCountMessage1.Text = strRowCountMessage1;
break;
case 2:
strRowCountMessage2 = itemsSelected + " of " + count + " ratings in Section " + i + " are checked.";
lblRowCountMessage2.Text = strRowCountMessage2;
break;
//case 3:
// strRowCountMessage3 = itemsSelected + " of " + count + " ratings in Section " + i + " are checked.";
// lblRowCountMessage3.Text = strRowCountMessage3;
// break;
//case 4:
// strRowCountMessage4 = itemsSelected + " of " + count + " ratings in Section " + i + " are checked.";
// lblRowCountMessage3.Text = strRowCountMessage4;
// break;
//case 5:
// strRowCountMessage5 = itemsSelected + " of " + count + " ratings in Section " + i + " are checked.";
// lblRowCountMessage3.Text = strRowCountMessage5;
// break;
//case 6:
// strRowCountMessage6 = itemsSelected + " of " + count + " ratings in Section " + i + " are checked.";
// lblRowCountMessage3.Text = strRowCountMessage6;
// break;
}//end switch
}//end if item.Selected = True
}//end foreach ListItem
}//end foreach gridviewrow
}//end if gv !=null
}// end for loop i
GridView1.DataBind();
GridView2.DataBind();
//GridView4.DataBind();
//GridView5.DataBind();
//GridView6.DataBind();
}
看看这有助于:。 –
TambaySaPinas
感谢您对我的问题感兴趣。该链接是关于查找radiobuttonlist项目值,但我的代码成功获取该信息。我的代码错误在“foreach(GridViewrow row in gv.Rows)”,如果运行,但在调试期间找到正确的网格和单选按钮列表项。 – Doreen
我认为问题与先不检查空网格有关... – Doreen