我有一个下载列表,我绑定到数据表。以下是我用来执行此操作的代码:
ddlBuildAddr.DataSource = buildings
ddlBuildAddr.DataTextField = "buildingName"
ddlBuildAddr.DataValueField = "buildingId"
Dim addressId As Int32 = OfficeData.GetInstance().GetBuildingId(currentAddress)
ddlBuildAddr.SelectedIndex = addressId
ddlBuildAddr.DataBind()
不幸的是,行ddlBuildAddr.SelectedIndex = addressId
失败了。通过调试器查看此行,SelectedIndex
转到-1,而addressId
转到2.什么给出?为什么赋值运算符flatout不起作用?
答案 0 :(得分:5)
在尝试设置所选索引之前,将ddlDeptName.DataBind()移动到。在绑定之前,下拉列表中实际上没有任何项目,因此索引2无效。
答案 1 :(得分:1)
替换此行
ddlDeptName.SelectedIndex = addressId
有了这个:
ddlDeptName.SelectedValue = addressId.ToString()
至于失败的原因 - addressId可能超出了下拉列表中可能的索引值范围。
答案 2 :(得分:0)
我认为您需要设置SelectedValue
属性。
答案 3 :(得分:0)
第二,所选索引不是数据值或选定值成员。它是下拉列表项中ListItem的索引,dropdown [dropdown.selectedindex]将为您提供标记为选中的列表中的项目。因此,您必须找到要选择的项目,然后将selectedindex设置为该项目的索引。
来自MSDN的VB示例:
' Selects the item whose text is Apples
ListBox1.Items.FindByText("Apples")
If Not li Is Nothing Then
li.Selected = True
End If
// Selects the item whose text is Apples
ListItem li = ListBox1.Items.FindByText("Apples");
if(li != null)
{
li.Selected = true;
}
答案 4 :(得分:0)
使用此
ddlBuildAddr.DataSource = buildings
ddlBuildAddr.DataTextField = "buildingName"
ddlBuildAddr.DataValueField = "buildingId"
Dim addressId As Int32 = OfficeData.GetInstance().GetBuildingId(currentAddress)
ddlBuildAddr.Databind()
在
foreach (var item in ddlBuildAddr.Items)
{
if(Convert.toInt32(item.value)==addressId)
{
item.selected=true;
break;
}
}
答案 5 :(得分:0)
按如下方式更改您的代码....
ddlBuildAddr.DataSource = buildings
ddlBuildAddr.DataTextField = "buildingName"
ddlBuildAddr.DataValueField = "buildingId"
ddlBuildAddr.DataBind()
Dim addressId As Int32 = OfficeData.GetInstance().GetBuildingId(currentAddress)
ddlBuildAddr.SelectedValue = addressId //It may throw error if item is not found in the list
(or)
ddlBuildAddr.Items.FindByValue(addressId).Selected = true;
(or)
ListItem lstNew = ddlBuildAddr.Items.FindByValue(addressId)
ddlBuildAddr.selectedItem = lstNew