将变量写入VB.Net中预先存在的数组

将变量写入VB.Net中预先存在的数组,vb.net,arrays,listbox,Vb.net,Arrays,Listbox,我目前正在使用Framework4.0为一家电影院设计一个客户预订系统的模型。目前的所有数据都将存储在一个数组中,因为它是一个模型,所以它将保留它们的(客户名称、票价等),因为此时不需要永久存储数据 我有一个GUI表单和两个主要类,MainForm.vb用于处理应用程序的I/O功能,SeatManager.vb用于管理要运行以使程序运行的后台方法。每个类别的代码如下所示:- **MainForm.vb Class** Public Class MainForm Priva

我目前正在使用Framework4.0为一家电影院设计一个客户预订系统的模型。目前的所有数据都将存储在一个数组中,因为它是一个模型,所以它将保留它们的(客户名称、票价等),因为此时不需要永久存储数据

我有一个GUI表单和两个主要类,MainForm.vb用于处理应用程序的I/O功能,SeatManager.vb用于管理要运行以使程序运行的后台方法。每个类别的代码如下所示:-

**MainForm.vb Class**
    Public Class MainForm
        Private Const m_totalNumberOfSeats As Integer = 60
        Private m_seatManager As SeatManager

        Public Sub New()

            InitializeComponent()
            m_seatManager = New SeatManager(m_totalNumberOfSeats)
            InitializeGUI()
        End Sub

        ''' <summary>
        ''' Method called from the MainForm() method. This method is called when the form
        ''' is opened by the program (on initialisation).
        ''' </summary>
        Private Sub InitializeGUI()
            rbtnReservation.Checked = True              'Sets the Reserve button as being chosen
            lstReservations.Items.Clear()               'Clears the list displaying all seats and reservations
            txtCustomerName.Text = String.Empty         'Sets the name textbox as emtpy
            txtSeatPrice.Text = String.Empty

            cmbDisplayOptions.Items.AddRange([Enum].GetNames(GetType(SeatManager.DisplayOptions)))
            cmbDisplayOptions.SelectedIndex = SeatManager.DisplayOptions.AllSeats

            For i As Integer = 0 To m_totalNumberOfSeats - 1
                lstReservations.Items.Add(GetMyString(i))
            Next
        End Sub
        Private Function GetMyString(ByVal i As Integer) As String
            If i >= 0 AndAlso i < m_totalNumberOfSeats Then
                Return String.Format("{0}{1}{2}{3}", GetPaddedString(m_seatManager.MyArray(i, 0), 29), _
                                     GetPaddedString(m_seatManager.MyArray(i, 1), 41), _
                                     GetPaddedString(m_seatManager.MyArray(i, 2), 63), _
                                     m_seatManager.MyArray(i, 3))
            Else
                Return String.Empty
            End If
        End Function

        Private Function GetPaddedString(ByVal o As Object, ByVal length As Integer) As String
            Dim s As String = String.Empty
            If o IsNot Nothing Then s = o.ToString()
            If s.Length > length Then s = s.Substring(0, length)
            Return s.PadRight(length - s.Length)
        End Function

        '--Event Handler when you change the value of Customer Name/Price
        '    Dim index As Integer = lstBox.selectedIndex
        'm_arrayClass.PopulateArray(index,customerName.text, ctype(price.text,double))
        'lstBox.Items(index) = GetMyString(index)

        'Private Function CheckSelectedIndex() As Boolean
        '    If lstReservations.SelectedIndex <= 0 Then
        '        Return lstReservations.SelectedIndex
        '    Else
        '        Return False
        '    End If
        'End Function

        ''' <summary>
        ''' Method uses to verify that the user has entered text within the txtName textbox
        ''' </summary>
        ''' <param name="name">String variable passing the customer name inputted by the user</param>
        ''' <returns>True if validation confirms user has entered at least one character in
        ''' the txtName field otherwise returns False. If returns false, an error message will
        ''' be displayed to the user</returns>
        Private Function ReadAndValidateName(ByRef name As String) As Boolean
            If (String.IsNullOrEmpty(txtCustomerName.Text)) Or (String.IsNullOrEmpty(txtCustomerName.Text)) Then
                MessageBox.Show("You have not entered a valid customer name. Please try again", _
                                "Invalid Customer Name", MessageBoxButtons.OK)
                txtCustomerName.Focus()
                txtCustomerName.SelectAll()
                Return False
            Else
                Return True
            End If
        End Function

        ''' <summary>
        ''' This method calls the GetDouble() method in the InputUtility class to convert the text
        ''' given by the user in the txtPrice textbox. 
        ''' </summary>
        ''' <param name="seatPrice">Output parameter receiving the converted value</param>
        ''' <returns>True if conversion is successful and validates or False. If returns False
        ''' an error message will be displayed to the user.</returns>
        Private Function ReadAndValidatePrice(ByRef seatPrice As Double) As Boolean
            If (InputUtility.GetDouble(txtSeatPrice.Text, seatPrice) And (seatPrice >= 0)) Then
                Return True
            Else
                MessageBox.Show("You have not entered a valid price. Please try again", _
                                "Invalid Price", MessageBoxButtons.OK)
                txtSeatPrice.Focus()
                txtSeatPrice.SelectAll()
                Return False
            End If
        End Function

        ''' <summary>
        ''' This method calls the above two methods (validate name and validate price) and if both return true, 
        ''' this method also returns true. If either of the above two methods are false, this method returns false
        ''' </summary>
        ''' <param name="name">Output Parameter - customer name</param>
        ''' <param name="seatPrice">Output parameter - seat price</param>
        ''' <returns>Returns true if validates and false if not</returns>
        Private Function ReadAndValidateInput(ByRef name As String, ByRef seatPrice As Double) As Boolean
            Dim nameResult As Boolean = ReadAndValidateName(name)
            Dim priceResult As Boolean = ReadAndValidatePrice(seatPrice)

            Return ((nameResult) And (priceResult))
        End Function

        Private Sub btnExitApplication_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExitApplication.Click

            Dim msgConfirmation As Integer
            msgConfirmation = MessageBox.Show("Are You Sure You Wish To Exit This Application?", "WARNING!", _
                                              MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation)
            If msgConfirmation = vbYes Then
                Application.Exit()
            End If
        End Sub
    End Class




**SeatManager.vb Class**            
    Public Class SeatManager
        Private _array(,) As Object
        Dim m_totalNumberOfSeats As Integer

        Public Sub New(ByVal maxNumberOfSeats As Integer)
            m_totalNumberOfSeats = maxNumberOfSeats
            ReDim _array(m_totalNumberOfSeats - 1, 3)
            For i As Integer = 0 To m_totalNumberOfSeats - 1
                PopulateArray(i, Nothing, 0.0)
            Next
        End Sub

        Public ReadOnly Property MyArray() As Object(,)
            Get
                Return _array
            End Get
        End Property

        Public Enum DisplayOptions
            AllSeats
            VacantSeats
            ReservedSeats
        End Enum

        Public Sub PopulateArray(ByVal i As Integer, ByVal CustomerName As String, ByVal Price As Double)
            Dim av As String = "Available"
            If Not String.IsNullOrEmpty(CustomerName) Then av = "Not Available"
            'Did you say this has to be handled in an enum?

            _array(i, 0) = i + 1 'Seat Number
            _array(i, 1) = av
            _array(i, 2) = CustomerName
            _array(i, 3) = Price
        End Sub
    End Class
**MainForm.vb类**
公共类主窗体
Private Const m_totalNumberOfSeats As Integer=60
私人m_seatManager作为seatManager
公共分新()
初始化组件()
m_seatManager=新的seatManager(m_totalNumberOfSeats)
初始化gui()
端接头
''' 
从MainForm()方法调用“”方法。当窗体
''由程序打开(初始化时)。
''' 
私有子初始化gui()
rbtnReservation.Checked=True'将保留按钮设置为选中状态
lstReservations.Items.Clear()'清除显示所有座位和预订的列表
txtCustomerName.Text=String.Empty'将名称文本框设置为emtpy
txtSeatPrice.Text=String.Empty
cmbDisplayOptions.Items.AddRange([Enum].GetNames(GetType(SeatManager.DisplayOptions)))
CMB DisplayOptions.SelectedIndex=SeatManager.DisplayOptions.AllSeats
对于i作为整数=0到m_totalNumberOfSeats-1
lstpreservations.Items.Add(GetMyString(i))
下一个
端接头
私有函数GetMyString(ByVal i作为整数)作为字符串
如果i>=0,并且i长度,则s=s.子字符串(0,长度)
返回s.PadRight(长度-s.length)
端函数
'--更改客户名称/价格的值时的事件处理程序
'将索引设置为整数=lstBox.selectedIndex
'm_arrayClass.PopulateArray(索引、customerName.text、ctype(price.text、double))
'lstBox.Items(索引)=GetMyString(索引)
'私有函数CheckSelectedIndex()为布尔值

'如果lstReservations.SelectedIndex,这里有一种使用类型化数据集和xml实现内存中数据库的非常简单的方法。您可以创建一个类型化数据集来将数据保存在内存中,甚至可以使用关系数据库结构来确保数据的完整性。您可以在内存中对此数据进行更改,并将数据保存到XML文件中,然后在下次运行时重新加载该文件,也可以放弃该文件,并在每次运行时重新构建该文件

下面是一些用于创建示例数据和填充数据集的示例代码。您可以编写代码在运行时像查询真实数据库一样查询数据集

    Dim SampleDataFileName = "c:\sampledata.xml"

    Dim ds As New dsReservations

    Try
        ds.ReadXml(SampleDataFileName)
    Catch ex As Exception

    End Try

    If ds.Event.Rows.Count = 0 Then
        'No data yet...initialize sample
        ds.Seat.AddSeatRow(1, "21B")
        ds.Seat.AddSeatRow(2, "21C")
        ds.Seat.AddSeatRow(3, "21D")

        ds.Customer.AddCustomerRow(1, "Bob")
        ds.Customer.AddCustomerRow(2, "Ed")
        ds.Customer.AddCustomerRow(3, "Sally")

        ds.Event.AddEventRow(1, #1/1/2012#, "Concert in the park")
        ds.Event.AddEventRow(2, #5/1/2012#, "Parade")



        Dim drRes1 = ds.Reservation.NewReservationRow
        drRes1.EventId = 1
        drRes1.SeatId = 2
        drRes1.CustomerId = 2
        ds.Reservation.AddReservationRow(drRes1)

        'Save our sample data
        ds.WriteXml(SampleDataFileName)
    End If

    'Spit out all our data (ASP.NET)'
    Response.Write(ds.GetXml())
这是数据集,将其命名为“dsReservations.xsd”。它有四个相关的表(事件、座位、客户和预订)



有很多关于如何查询类型化数据表的例子。享受吧

不幸的是,你给我们的代码太多了。您是否可以隔离问题区域,只显示解释问题所需的代码。此外,尽管您说不需要持久化数据,但我还是建议您研究某种形式的数据持久化,XML或数据库(SQL Express和SQLite都是免费的)或其他形式。使用数组有时会让你发疯,使用多维数组会让你更加发疯!你遇到的问题可以通过数据库很容易地解决。如果你要坚持非持久性,那么至少看看
System.collections
下的集合,比如
List(Of T)
。我同意Chris的观点:使用一个List(Of T)填充表示实体的类实例(Reservation类、Customer类等),而不是二维数组。这将更容易使用,即使是对于模型。
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="dsReservations" targetNamespace="http://tempuri.org/dsReservations.xsd" xmlns:mstns="http://tempuri.org/dsReservations.xsd" xmlns="http://tempuri.org/dsReservations.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:msprop="urn:schemas-microsoft-com:xml-msprop" attributeFormDefault="qualified" elementFormDefault="qualified">
  <xs:annotation>
    <xs:appinfo source="urn:schemas-microsoft-com:xml-msdatasource">
      <DataSource DefaultConnectionIndex="0" FunctionsComponentName="QueriesTableAdapter" Modifier="AutoLayout, AnsiClass, Class, Public" SchemaSerializationMode="IncludeSchema" xmlns="urn:schemas-microsoft-com:xml-msdatasource">
        <Connections />
        <Tables />
        <Sources />
      </DataSource>
    </xs:appinfo>
  </xs:annotation>
  <xs:element name="dsReservations" msdata:IsDataSet="true" msdata:UseCurrentLocale="true" msprop:Generator_DataSetName="dsReservations" msprop:Generator_UserDSName="dsReservations">
    <xs:complexType>
      <xs:choice minOccurs="0" maxOccurs="unbounded">
        <xs:element name="Customer" msprop:Generator_TableClassName="CustomerDataTable" msprop:Generator_TableVarName="tableCustomer" msprop:Generator_TablePropName="Customer" msprop:Generator_RowDeletingName="CustomerRowDeleting" msprop:Generator_UserTableName="Customer" msprop:Generator_RowChangingName="CustomerRowChanging" msprop:Generator_RowEvHandlerName="CustomerRowChangeEventHandler" msprop:Generator_RowDeletedName="CustomerRowDeleted" msprop:Generator_RowEvArgName="CustomerRowChangeEvent" msprop:Generator_RowChangedName="CustomerRowChanged" msprop:Generator_RowClassName="CustomerRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="CustomerId" msprop:Generator_ColumnVarNameInTable="columnCustomerId" msprop:Generator_ColumnPropNameInRow="CustomerId" msprop:Generator_ColumnPropNameInTable="CustomerIdColumn" msprop:Generator_UserColumnName="CustomerId" type="xs:int" />
              <xs:element name="CustomerName" msprop:Generator_ColumnVarNameInTable="columnCustomerName" msprop:Generator_ColumnPropNameInRow="CustomerName" msprop:Generator_ColumnPropNameInTable="CustomerNameColumn" msprop:Generator_UserColumnName="CustomerName" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Event" msprop:Generator_TableClassName="EventDataTable" msprop:Generator_TableVarName="tableEvent" msprop:Generator_TablePropName="Event" msprop:Generator_RowDeletingName="EventRowDeleting" msprop:Generator_UserTableName="Event" msprop:Generator_RowChangingName="EventRowChanging" msprop:Generator_RowEvHandlerName="EventRowChangeEventHandler" msprop:Generator_RowDeletedName="EventRowDeleted" msprop:Generator_RowEvArgName="EventRowChangeEvent" msprop:Generator_RowChangedName="EventRowChanged" msprop:Generator_RowClassName="EventRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="EventId" msprop:Generator_ColumnVarNameInTable="columnEventId" msprop:Generator_ColumnPropNameInRow="EventId" msprop:Generator_ColumnPropNameInTable="EventIdColumn" msprop:Generator_UserColumnName="EventId" type="xs:int" />
              <xs:element name="EventDate" msprop:Generator_ColumnVarNameInTable="columnEventDate" msprop:Generator_ColumnPropNameInRow="EventDate" msprop:Generator_ColumnPropNameInTable="EventDateColumn" msprop:Generator_UserColumnName="EventDate" type="xs:dateTime" minOccurs="0" />
              <xs:element name="EventName" msprop:Generator_ColumnVarNameInTable="columnEventName" msprop:Generator_ColumnPropNameInRow="EventName" msprop:Generator_ColumnPropNameInTable="EventNameColumn" msprop:Generator_UserColumnName="EventName" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Seat" msprop:Generator_TableClassName="SeatDataTable" msprop:Generator_TableVarName="tableSeat" msprop:Generator_TablePropName="Seat" msprop:Generator_RowDeletingName="SeatRowDeleting" msprop:Generator_UserTableName="Seat" msprop:Generator_RowChangingName="SeatRowChanging" msprop:Generator_RowEvHandlerName="SeatRowChangeEventHandler" msprop:Generator_RowDeletedName="SeatRowDeleted" msprop:Generator_RowEvArgName="SeatRowChangeEvent" msprop:Generator_RowChangedName="SeatRowChanged" msprop:Generator_RowClassName="SeatRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="SeatId" msprop:Generator_ColumnVarNameInTable="columnSeatId" msprop:Generator_ColumnPropNameInRow="SeatId" msprop:Generator_ColumnPropNameInTable="SeatIdColumn" msprop:Generator_UserColumnName="SeatId" type="xs:int" />
              <xs:element name="SeatLocation" msprop:Generator_ColumnVarNameInTable="columnSeatLocation" msprop:Generator_ColumnPropNameInRow="SeatLocation" msprop:Generator_ColumnPropNameInTable="SeatLocationColumn" msprop:Generator_UserColumnName="SeatLocation" type="xs:string" minOccurs="0" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
        <xs:element name="Reservation" msprop:Generator_TableClassName="ReservationDataTable" msprop:Generator_TableVarName="tableReservation" msprop:Generator_TablePropName="Reservation" msprop:Generator_RowDeletingName="ReservationRowDeleting" msprop:Generator_UserTableName="Reservation" msprop:Generator_RowChangingName="ReservationRowChanging" msprop:Generator_RowEvHandlerName="ReservationRowChangeEventHandler" msprop:Generator_RowDeletedName="ReservationRowDeleted" msprop:Generator_RowEvArgName="ReservationRowChangeEvent" msprop:Generator_RowChangedName="ReservationRowChanged" msprop:Generator_RowClassName="ReservationRow">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="EventId" msprop:Generator_ColumnVarNameInTable="columnEventId" msprop:Generator_ColumnPropNameInRow="EventId" msprop:Generator_ColumnPropNameInTable="EventIdColumn" msprop:Generator_UserColumnName="EventId" type="xs:int" />
              <xs:element name="SeatId" msprop:Generator_ColumnVarNameInTable="columnSeatId" msprop:Generator_ColumnPropNameInRow="SeatId" msprop:Generator_ColumnPropNameInTable="SeatIdColumn" msprop:Generator_UserColumnName="SeatId" type="xs:int" />
              <xs:element name="CustomerId" msprop:Generator_ColumnVarNameInTable="columnCustomerId" msprop:Generator_ColumnPropNameInRow="CustomerId" msprop:Generator_ColumnPropNameInTable="CustomerIdColumn" msprop:Generator_UserColumnName="CustomerId" type="xs:int" />
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:choice>
    </xs:complexType>
    <xs:unique name="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:Customer" />
      <xs:field xpath="mstns:CustomerId" />
    </xs:unique>
    <xs:unique name="Event_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:Event" />
      <xs:field xpath="mstns:EventId" />
    </xs:unique>
    <xs:unique name="Seat_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:Seat" />
      <xs:field xpath="mstns:SeatId" />
    </xs:unique>
    <xs:unique name="Reservation_Constraint1" msdata:ConstraintName="Constraint1" msdata:PrimaryKey="true">
      <xs:selector xpath=".//mstns:Reservation" />
      <xs:field xpath="mstns:EventId" />
      <xs:field xpath="mstns:SeatId" />
    </xs:unique>
    <xs:unique name="Constraint2">
      <xs:selector xpath=".//mstns:Reservation" />
      <xs:field xpath="mstns:EventId" />
    </xs:unique>
    <xs:keyref name="FK_Event_Reservation" refer="Event_Constraint1" msprop:rel_Generator_UserChildTable="Reservation" msprop:rel_Generator_ChildPropName="GetReservationRows" msprop:rel_Generator_ParentPropName="EventRow" msprop:rel_Generator_UserRelationName="FK_Event_Reservation" msprop:rel_Generator_RelationVarName="relationFK_Event_Reservation" msprop:rel_Generator_UserParentTable="Event">
      <xs:selector xpath=".//mstns:Reservation" />
      <xs:field xpath="mstns:EventId" />
    </xs:keyref>
    <xs:keyref name="FK_Seat_Reservation" refer="Seat_Constraint1" msprop:rel_Generator_UserChildTable="Reservation" msprop:rel_Generator_ChildPropName="GetReservationRows" msprop:rel_Generator_ParentPropName="SeatRow" msprop:rel_Generator_UserRelationName="FK_Seat_Reservation" msprop:rel_Generator_RelationVarName="relationFK_Seat_Reservation" msprop:rel_Generator_UserParentTable="Seat">
      <xs:selector xpath=".//mstns:Reservation" />
      <xs:field xpath="mstns:SeatId" />
    </xs:keyref>
    <xs:keyref name="FK_Customer_Reservation" refer="Constraint1" msprop:rel_Generator_UserChildTable="Reservation" msprop:rel_Generator_ChildPropName="GetReservationRows" msprop:rel_Generator_ParentPropName="CustomerRow" msprop:rel_Generator_UserRelationName="FK_Customer_Reservation" msprop:rel_Generator_RelationVarName="relationFK_Customer_Reservation" msprop:rel_Generator_UserParentTable="Customer">
      <xs:selector xpath=".//mstns:Reservation" />
      <xs:field xpath="mstns:CustomerId" />
    </xs:keyref>
  </xs:element>
</xs:schema>