它看起來你的代碼應該是
var alList = new List<string>();
foreach (GridViewRow row in gvDetails.Rows)
{
string strID = ((Label)row.FindControl("lblID")).Text;
string strGroup = ((Label)row.FindControl("lblGrp")).Text;
string strValue = ((TextBox)row.FindControl("txtValue")).Text;
alList.Add(strID);
alList.Add(strGroup);
alList.Add(strValue);
}
否則你想加入到列表變量超出範圍(因爲strID
和其他已申報環內範圍內)
注:不要使用ArrayList
它已經過時。在你的情況下,最好使用List<string>
代替。
或者,如果我錯過了你的觀點,你需要添加到列表從最後一次迭代唯一變量(因爲它可以從你的代碼中應該) - 然後聲明strID
和其他變量外循環,就像這樣:
string strID = null, strGroup = null, strValue = null;
var alList = new List<string>();
foreach (GridViewRow row in gvDetails.Rows)
{
strID = ((Label)row.FindControl("lblID")).Text;
strGroup = ((Label)row.FindControl("lblGrp")).Text;
strValue = ((TextBox)row.FindControl("txtValue")).Text;
}
alList.Add(strID);
alList.Add(strGroup);
alList.Add(strValue);
更新
因爲我們在評論中已經明確你的目標,其實你不必List<string>
而是DataTable
,你的代碼可能是這樣的:
var dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Group", typeof(string));
dt.Columns.Add("Value", typeof(string));
foreach (GridViewRow row in gvDetails.Rows)
{
var dro = dt.NewRow();
dro["ID"] = ((Label)row.FindControl("lblID")).Text;
dro["Group"] = ((Label)row.FindControl("lblGrp")).Text;
dro["Value"] = ((TextBox)row.FindControl("txtValue")).Text;
dt.Rows.Add(dro);
}
另請注意 - datatable列的數據類型可以是任何字符串,而不僅僅是字符串 - 它取決於您要存儲的實際數據。
爲什麼不使用調試器來通過列表......你會很快看到你沒有正確地做什麼的地方..你需要爲啓動器定義alList作爲可訪問循環之外的變量在類級別,如果你打算使用它並且或者在應用程序的其他地方獲得對它的訪問..如果不是在循環外部聲明並創建一個List對象變量..那麼在循環內部添加字符串變量到列表親自你會更好地創建一個類對象,並在那裏存儲數據 –
MethodMan
我也建議你谷歌如何創建一個數據表,其中包含3個字段,您正在嘗試使用和或創建... – MethodMan
aint this sa我問邁克爾問了嗎? http://stackoverflow.com/revisions/29794413/1 – naveen