如何将两个数据库列值检索为文本框,以逗号分隔的字符串?

时间:2010-12-30 09:23:46

标签: asp.net vb.net

如果我有两个文本框textbox1&我的ASP.NET和SQL Server数据库中的textbox2和button1

数据库记录是:

ID         Date               Seats
1          15-Dec-2010        1,2   
2          15-Dec-2010        3,4
3          17-Dec-2010        1,2,3,4

我希望当我在TextBox1中键入15-Dec-2010并单击Button1然后在textbox2中使用SELECT查询从数据库中检索输出然后在TextBox2中输出将显示为1,2,3,4

确切地说我想使用SELECT查询和VB.NET。

2 个答案:

答案 0 :(得分:1)

我建议使用Calendar-Control。您应该使用ASP.Net CompareValidator进行验证。您应该在客户端和服务器端检查以避免例外:

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox1" Type="Date" Operator="DataTypeCheck" runat="server" ErrorMessage="Enter a valid Date!" EnableClientScript="true" ></asp:CompareValidator>
<asp:Button ID="BtnGetSeats" runat="server" Text="get seats" />

在服务器端,您还应该触发验证(例如,如果禁用了javascript)。 回答您的实际问题(未经测试):

Private Sub BtnGetSeats_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnGetSeats.Click
     Page.Validate()
     If Me.IsValid Then
         Dim connectionString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"
         Dim commandText As String = "SELECT Seats FROM Table1 WHERE [Date] = @Date"
         Dim allSeats As New List(Of String)
         Using connection As New SqlConnection(connectionString)
            Try
               Dim command As New SqlCommand(commandText, connection)
               command.Parameters.AddWithValue("@Date", Date.Parse(Me.Textbox1.Text))
               connection.Open()
               Using reader As SqlDataReader = command.ExecuteReader
                  While reader.Read
                    Dim nextSeats As String = Convert.ToString(reader(0))
                    allSeats.AddRange(nextSeats.Split(","c))
                  End While
               End Using
           Catch ex As Exception
              Throw 'you should log exceptions'
           End Try
        End Using
        'list all seats comma separated in TextBox2'
        TextBox2.Text = String.Join(",", allSeats.ToArray)
    End If
End Sub

答案 1 :(得分:0)

  1. 使用JavaScript填充文本框中的文本

  2. 将表单提交到服务器

  3. 当返回的服务器的结果显示结果