這可能是一個簡單的問題,但我正在用DropDownList在C#中開發一個Web應用程序。目前它僅用於一個DropDownList。但是現在我修改了代碼,使得應該出現的DropDownLists的數量是動態的,它給了我錯誤;如何在ASP.NET中動態返回DropDownList選擇?
「 當前上下文中不存在名稱'ddl'。」
此錯誤的原因是有多個'ddl'=計數器數量的實例。那麼我該如何返回多個'ddl'?就像這種方法有什麼返回類型呢?如何返回這些值?
我需要動態的原因是我需要爲他們選擇的任何Adventureworks表中的每列創建一個DropDownList。
private DropDownList CreateDropDownLists()
{
for (int counter = 0; counter < NumberOfControls; counter++)
{
DropDownList ddl = new DropDownList();
SqlDataReader dr2 = ADONET_methods.DisplayTableColumns(targettable);
ddl.ID = "DropDownListID" + (counter + 1).ToString();
int NumControls = targettable.Length;
DataTable dt = new DataTable();
dt.Load(dr2);
ddl.DataValueField = "COLUMN_NAME";
ddl.DataTextField = "COLUMN_NAME";
ddl.DataSource = dt;
ddl.ID = "DropDownListID 1";
ddl.SelectedIndexChanged += new EventHandler(ddlList_SelectedIndexChanged);
ddl.DataBind();
ddl.AutoPostBack = true;
ddl.EnableViewState = true; //Preserves View State info on Postbacks
//ddlList.Style["position"] = "absolute";
//ddl.Style["top"] = 80 + "px";
//ddl.Style["left"] = 0 + "px";
dr2.Close();
}
return ddl;
}
很好的答案!我用這個解決方案,凱文! – salvationishere 2010-04-10 11:34:50