C# DropDownList始终选择错误的列表项
在我的网页上进行选择并单击保存按钮后,我始终会收到C# DropDownList始终选择错误的列表项,c#,asp.net,C#,Asp.net,在我的网页上进行选择并单击保存按钮后,我始终会收到“0”值列表项。我希望得到选择的任何东西,而不是总是得到同样的东西 我的代码是从摄像机获取一系列分辨率,并将它们按正确的顺序放入下拉列表中(ddlsolution) 主要代码: //there is code above but ~should~ be irrelevant //selectedCam is a custom object. its the video camera if (selectedCam != null) {
“0”
值列表项
。我希望得到选择的任何东西,而不是总是得到同样的东西
我的代码是从摄像机获取一系列分辨率,并将它们按正确的顺序放入下拉列表中(ddlsolution
)
主要代码:
//there is code above but ~should~ be irrelevant
//selectedCam is a custom object. its the video camera
if (selectedCam != null)
{
//this will get an array of resolutions for this camera
string[] res = selectedCam.GetValidResolutionsAsArray();
ddlResolution.ClearSelection();
ddlResolution.Items.Clear();
//putt resolutions in correct order
if (res.Length >= 3)
{
AddItem(ddlResolution, GetResolutionQualityString(1, res), "1");
AddItem(ddlResolution, GetResolutionQualityString(0, res), "0");
//ignore extra small resolutions...thats why we skip "2"
//check to see if the last resolution a duplicate
string hd = string.Format((string)GetLocalResourceObject("ResMedium"), res[3]);
if (res.Length >= 4 && ddlResolution.Items.FindByText(hd) == null)
AddItem(ddlResolution, GetResolutionQualityString(3, res), "3");
}
if (!resolutionSelected) SelectValue("0", ddlResolution);
}
上述代码中使用的方法:
private static void AddItem(DropDownList ddl, string text, string value)
{
ddl.Items.Add(new ListItem(text, value));
}
//gets strings from a resource file
private string GetResolutionQualityString(int i, string[] res)
{
if (res == null || res.Length <= 0) return "";
switch (i)
{
case 0: return string.Format((string)GetLocalResourceObject("ResMedium"), res[i]);
case 1: return string.Format((string)GetLocalResourceObject("ResLow"), res[i]);
case 3: return string.Format((string)GetLocalResourceObject("ResHigh"), res[i]);
default: return "";
}
}
private void SelectValue(string value, ListControl rbList)
{
foreach (ListItem li in rbList.Items)
if (li.Value == value)
li.Selected = true;
}
无论我选择什么,都会得到以下结果:
2014-07-02
17:54:25.049 7812类名信息ddlResolution.SelectedValue=
0
2014-07-02
17:54:30.844 5556类名信息DDLSolution.SelectedValue=
0
2014-07-02
17:54:35.008 7504类名信息ddlResolution.SelectedValue=
0
所谓的Main code
-在何处以及如何调用?是否验证当前加载不是回发?@Andrei否。下拉列表是否应更新回发。更改下拉列表时,在回发过程中有什么特别需要做的吗?@Andrei抱歉,我忘了提到resolutionSelected
。前面的部分代码将尝试从数据库中选择存储的值。另外,我将此if(selectedCam!=null)
更改为if(!IsPostBack&&selectedCam!=null)
。这在很大程度上起了作用。然而,我不太明白为什么会有这样的把戏。在每次回发时,您实际上会重置ddl的整个状态(通过清除所有项)。而选择是这种状态的一部分,因此它会丢失。但是,如果您的ddl绑定总是相同的(在每次回发时)-您可以执行一次,并且ASP.NET将通过回发以及选择来维护项目列表。那么你用做了什么呢!IsPostBack
实际上是“一次加载所有项目,然后在以后的回发中使用它们”。这清楚吗?
log.Info("ddlResolution.SelectedValue = " + ddlResolution.SelectedValue);//TODO REMOVE