这可能是一个简单的问题,但我正在使用DropDownList在C#中开发一个Web应用程序。目前它只适用于一个DropDownList。但是现在我修改了代码,以便应该出现的DropDownLists数量是动态的,它给了我错误;
“名称'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;
}
答案 0 :(得分:1)
看起来你试图在函数结束时返回下拉列表,但是它在for循环的范围内声明了。尝试在函数开头创建一个下拉数组(在for循环之前),然后在循环内设置数组然后返回它。您还需要更改函数声明以支持一系列下拉。
private DropDownList[] CreateDropDownLists()
{
DropDownList[] dropDowns = new DropDownList[NumberOfControls];
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();
dropDowns[counter] = ddl;
}
return dropDowns;
}
答案 1 :(得分:1)
为什么不直接返回DropDownList列表?
private List<DropDownList> CreateDropDownLists()
{
List<DropDownList> listDDL = new List<DropDownList>();
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();
listDDL.Add(ddl);
}
return listDDL;
}