DropDownList.SelectedIndex sets to 1



"DropDownList.SelectedIndex=-1";问题

我使用上面的解决方案来设置我的DropDownlist,它正在按预期工作。但我注意到有一个间歇性错误,在索引0处使用以下代码插入项目后
myDropDownList.Items.Insert(0, new ListItem("Please select", ""));
myDropDownList.SelectedIndex设置为1

你把它放在Page_Load上了吗?或者你有更多的信息?这里的小代码示例是VB.NET,但你应该明白这个想法。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
MyDropDownList.SelectedIndex = -1

End If

End Sub

***编辑这就是我在项目中的做法。(我在这里填写数据库的下拉列表。)

Private Sub Fill_DropDown()
dsItems= SqlHelper.ReadOnlyDataset("SELECT Item FROM Items ORDER BY ID")

ws_Items.Items.Add("Choose Item...")
For Each row As DataRow In dsItems.Tables(0).Rows
ws_Items.Items.Add(row("Items"))
Next
ws_Items.SelectedIndex = 0
End Sub

然后在负载上我做这个

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Call Fill_DropDown()
End If

End Sub

最新更新