数据绑定列表框selectedindex始终为-1

时间:2010-02-21 23:18:09

标签: asp.net vb.net listbox databound-controls

我有一个简单的上传表单。这是我的代码:

<form id="Form1" method="post" enctype="multipart/form-data" runat="server"
    <asp:label id="lblMsg" runat="server" CssClass="msg" />
    <span class="msg">Select Gallery:</span>
    <asp:listbox id="gallerySelect" runat="server" Rows="1" DataTextField="galleryName" DataValueField="galleryID" />
    <span class="msg">File:</span><input type="file" id="galleryLogo" name="galleryLogo" runat="server" />
    <input type="button" value="Upload" OnServerClick="Upload" runat="server"><br />
</form>

您应该能够选择要为其上传徽标图像的图库,然后选择图像文件并单击上传按钮。这是我的上传子:

Sub Upload(Source As Object, e As EventArgs)
    If Not (galleryLogo.PostedFile Is Nothing) Then
        Dim intFileNameLength as Integer
        Dim strFileNamePath as String
        Dim strFileNameOnly as String
        'Logic to find the FileName (excluding the path)
        strFileNamePath = galleryLogo.PostedFile.FileName
        intFileNameLength = Instr(1, StrReverse(strFileNamePath), "\")
        strFileNameOnly = Mid(strFileNamePath, (Len(strFileNamePath)-intFileNameLength)+2)
        galleryLogo.PostedFile.SaveAs("c:\inetpub\wwwroot\galleries\" & strFileNameOnly)

        Dim cmd As SqlCommand
        Cache("sqlconn") = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
        Cache("sqlconn").Open()
        Dim query = "update gallery set logo = '" & strFileNameOnly & "' where gallery_id = " & gallerySelect.SelectedItem.Value.ToString()
        cmd = New SqlCommand(query, Cache("sqlconn"))
        cmd.ExecuteNonQuery()   
        tell the user something positive
        lblMsg.Text = "File Uploaded Successfully<br />"
        End If
End Sub

我的问题是数据绑定列表框gallerySelect的selectedIndex始终为-1。我知道它,因为它的数据绑定,但我不知道我必须做什么才能获得价值。任何帮助将不胜感激。

编辑:

如果您需要,这是我的绑定代码:

Dim galleryCmdSelect2 As SqlCommand
Dim galleryData2 As SqlDataReader
galleryCmdSelect2 = New SqlCommand("select gallery_name as galleryName, gallery_id as galleryID from galleries order by gallery_name", Cache("sqlconn"))
galleryData2 = galleryCmdSelect2.ExecuteReader()
gallerySelect.DataSource = galleryData2
gallerySelect.DataBind()
galleryData2.Close()

1 个答案:

答案 0 :(得分:2)

如果您正在为每个回发数据绑定控件,这将清除SelectedValue,而是像这样包装您的数据绑定代码:

If Not (IsPostBack) Then
 //DataBind here
End If