我需要幫助遍歷頁面上的兩個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