0

我有一个下拉列表,我有一个数据源,我想添加它工作的空白数据,但选择的值始终为 0

我背后的代码:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
listhostel()   
End Sub

Protected Sub listhostel()
Dim dash As New DataSet
Dim clas As New Class1

dash = clas.returndataset("select ID as idhostel,Nama from Hostel")

listhotelx.DataSource = dash
listhotelx.DataBind()
listhotelx.Items.Insert(0, New ListItem("-- Select --", 0))
End Sub

Protected Sub viewdatagrid_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles viewdatagrid.Click    
Label1.Text = listhotelx.SelectedValue 
viewdata()
End Sub

文件.aspx

 <asp:DropDownList ID="listhotelx" runat="server" DataTextField="Nama"
 DataValueField="idhostel" >
        </asp:DropDownList>
4

4 回答 4

0

数据绑定并添加项目后,请注意如何设置项目 SelectedIndex:

listhotelx.Items.Insert(0, new ListItem("-- Select --", String.Empty));
listhotelx.SelectedIndex = 0;
于 2012-07-16T06:29:24.950 回答
0

你得到的错误是因为ListItemmust have(string,string)作为参数并且你传递("-- Select --",0)的是(string,int).

如果要在顶部添加空白数据,则只需输入空字符串。

listhotelx.Items.Insert(0, new ListItem(String.Empty, String.Empty));
listhotelx.SelectedIndex = 0;
于 2012-07-16T06:36:05.803 回答
0

在 Page_Load 上必须添加 Page.IsPostBack

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            listhostel()
        End If
    End Sub
于 2012-07-16T06:43:51.390 回答
0

将新项目添加到下拉列表后调用 DropDownList.DataBind() 方法。ListItem 方法只接受字符串值,因此在您的代码中将 0 替换为“0”

Protected Sub listhostel()
Dim dash As New DataSet
Dim clas As New Class1

dash = clas.returndataset("select ID as idhostel,Nama from Hostel")

listhotelx.DataSource = dash    
listhotelx.Items.Insert(0, New ListItem("-- Select --", "0")) // here the 2nd argument is string.
listhotelx.DataBind()
End Sub

//    I have checked this code and it works fine for me   

我还在我的下拉列表中添加了一个项目

<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
   <asp:ListItem Text="name1" Value="-1" ></asp:ListItem>
</asp:DropDownList>

在我添加新项目时单击按钮,它成功地将项目添加到索引 0。

 protected void Button1_Click(object sender, EventArgs e)
{
    DropDownList1.Items.Insert(0,new ListItem("name", "-1"));         
    DropDownList1.DataBind();
}
于 2012-07-16T06:24:37.453 回答