在顶部下拉列表中添加空白数据时出错

时间:2012-07-16 06:14:58

标签: asp.net vb.net

我有一个下拉列表,我有一个数据源,我想添加它工作的空白数据,但选择的值始终为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

file.aspx

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

4 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分:0)

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

listhotelx.Items.Insert(0, new ListItem("-- Select --", String.Empty));
listhotelx.SelectedIndex = 0;

答案 2 :(得分:0)

您收到错误,因为ListItem必须以(string,string)作为参数,而您传递("-- Select --",0) (string,int)

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

listhotelx.Items.Insert(0, new ListItem(String.Empty, String.Empty));
listhotelx.SelectedIndex = 0;

答案 3 :(得分: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