2013-07-30 217 views
0

我有一個下拉列表控件,它顯示來自名爲model的表的主鍵以及當我使用下拉列表時應顯示來自同一表的另一個值(外鍵)的文本框。 PK和FK都有一個值。選擇下拉列表值時更改文本框的值

由於我不知道如何做到這一點,我使用了一種搜索方法,每次有人從下拉列表中選擇一個新值時應該調用該方法。

搜索代碼:

Public Function searchArea(ByVal model As String) As String 

     Dim mycon As New Connection    

     Using connection As New SqlConnection(mycon.GetConnectionString()) 

      Using command As New SqlCommand() 

       command.Connection = connection 
       command.CommandType = CommandType.Text 
       command.CommandText = "SELECT area FROM model WHERE model= @model" 
       command.Parameters.AddWithValue("@model", model) 
       connection.Open() 

       Dim dataReader As SqlDataReader = command.ExecuteReader() 

       If (dataReader.Read()) Then 
        Return dataReader.ToString(0)'this query should always have a single value 
       End If 

       Return "Nothing" 

      End Using 

     End Using 

    End Function 

事件代碼:

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles DropDownList1.SelectedIndexChanged 
     Dim objModel As New ModelDAO 'the class where the method is 
     TextBox9.Text = objModel.searchArea(DropDownList1.Text) 
    End Sub 

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True" 
        DataSourceID="SqlDataSource1" DataTextField="MODEL" DataValueField="MODEL"> 
        <asp:ListItem Text="-Select-" Value="" /> 
        </asp:DropDownList> 
<asp:TextBox ID="TextBox9" runat="server" Enabled="False" Height="24px" 
         Width="219px"></asp:TextBox> 
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
      ConnectionString="<%$ ConnectionStrings:DBUserInterfaceConnectionString %>" 
      SelectCommand="SELECT [MODEL] FROM [MODEL]"> 
     </asp:SqlDataSource> 

但正如我想的那樣,它不起作用,你能幫我嗎?

編輯:謝謝,現在它觸發,但我得到的價值:'S'的價值不屬於我的表。可以告訴我,如果我的搜索方法是好的?

+2

AutoPostBack設置爲TRUE? – logixologist

+0

謝謝,現在它觸發,但是我沒有得到我想要的價值,我想我必須檢查我的sql語句。 – phalanx

+0

你的SQL返回什麼? – logixologist

回答

1

謝謝大家,我這個解決它:

而不是
Return dataReader.GetString(0) 

Return dataReader.ToString(0) 

這只是一個類型轉換問題。

3

嘗試添加該

<asp:DropDownList ID="DropDownList1" 
    runat="server" 
    AutoPostBack="true" 
    OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"> 
    ..... 
</asp:DropDownList> 
1

嘗試加載的DataReader到數據表,比用它來打印數據在文本框中..

相關問題