2013-12-11 33 views
0

我有一個ListBox填充SqlDataReader對象,它看起來不錯,但我遇到的問題是我希望數據文本字段顯示SQL查詢的date字段中的數據,並具有數據值爲ListBox來自url字段。如果您在Visual Studio 2010中使用查詢生成器功能,這非常容易。您只需單擊列表框並在右側屬性列中更改屬性即可。但是,由於我沒有使用查詢構建器功能,並且我正在手動編寫它,所以我無法弄清楚我的生活如何將列表框的數據文本字段更改爲date字段,並將數據值字段更改爲url字段。如何在保持項目顯示相同的情況下更改列表框中項目的值?

這背後的邏輯是,用戶將能夠點擊其項目的日期,單擊按鈕,它將導航到SQL Database中提供的url

這是我在按鈕單擊操作中使用的代碼;

Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SearchButton.Click 
    Dim startDate As Date 
    Dim endDate As Date 
    Dim connectionString As String 
    startDate = TextStartDate.Text 
    endDate = TextEndDate.Text 
    connectionString = SqlDataSource1.ConnectionString.ToString 

    Dim sqlConnection1 As New SqlConnection(connectionString) 
    Using sqlConnection1 
     Dim command As SqlCommand = New SqlCommand(_ 
            "SELECT first_name, last_name, date, url FROM tbl_paystubs WHERE date>='" + startDate.ToString + "' AND date<='" + endDate.ToString + "';", _ 
            sqlConnection1) 
     sqlConnection1.Open() 

     Dim reader As SqlDataReader = command.ExecuteReader() 

     While reader.Read 
      SearchListBox.Items.Add(reader.Item("url")) 
     End While 
     reader.Close() 
    End Using 
    sqlConnection1.Close() 

End Sub 

下面是一些圖片來幫助說明。

enter image description here

編輯:我想我這個問題有點令人費解,所以我要澄清一點。在ListBox裏面,那裏的項目現在顯示了搜索完成時的日期,我的問題是,我怎樣才能讓「打開」按鈕打開一個帶有ListBoxItems對應URL字段的瀏覽器窗口?

回答

0

我改變了下面的代碼來回答我的問題!

Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SearchButton.Click 
    Dim startDate As Date 
    Dim endDate As Date 

    startDate = TextStartDate.Text 
    endDate = TextEndDate.Text 

    Dim connectionString As String 
    startDate = TextStartDate.Text 
    endDate = TextEndDate.Text 
    connectionString = SearchDataSource.ConnectionString.ToString 

    Dim sqlConnection1 As New SqlConnection(connectionString) 
    Using sqlConnection1 
     Dim command As SqlCommand = New SqlCommand(_ 
     "SELECT first_name, last_name, date, url FROM tbl_paystubs WHERE date>='" + startDate.ToString + "' AND date<='" + endDate.ToString + "';", _ 
     sqlConnection1) 
     sqlConnection1.Open() 

     Dim da As New SqlDataAdapter(command) 
     Dim ds As New DataSet() 
     da.Fill(ds) 

     sqlConnection1.Close() 

     SearchListBox.DataSource = ds 
     SearchListBox.DataTextField = "date" 
     SearchListBox.DataValueField = "url" 
     SearchListBox.DataBind() 

    End Using 
    TextStartDate.Text = "" 
    TextEndDate.Text = "" 

End Sub 
0

你可以創建一個小的類是這樣的:

internal class LbItem 
{ 
    internal string url; 
    internal string data; 

    public override string ToString() 
    { 
     return this.data; 
    } 
} 

,並添加這個類的實例您ListBox.Items:

listBox1.Items.Add(new LbItem { url = "http:xyz", data = "123" }); 

列表框中將顯示LbItems被重寫爲返回ToString()函數...

+0

我在原始問題中添加了一個編輯。請參閱上面的建議。按鈕中的 –

+0

單擊事件處理程序LbItem item = listBox1.SelectedItem as LbItem;那麼你可以使用item.url來打開瀏覽器 – PrfctByDsgn

相關問題