DataGridView表单通信问题

问题描述 投票:0回答:1

我这里的代码就是我想要联系的人

Imports System.Globalization
Imports MySql.Data.MySqlClient


Public Class frmBooking
    Dim mycmd As New MySqlCommand
    Dim myconnection As New MySqlConnection("server='localhost';uid='root';pwd='';database='dbnoir'")
    Dim dataReader As MySqlDataReader

    Private selectedEventName As String
    Private selectedReservationDate As String
    Private selectedTimeOfReservation As String
    Private selectedReservationDuration As String
    Private selectedNumberOfExpectedGuests As String
    Private selectedDecoration As Boolean
    Private selectedCatering As Boolean
    Private selectedSoundAndLighting As Boolean
    Private selectedPhotoAndVideo As Boolean

    Private Sub frmBooking_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        cmbReservationDuration.Items.Add("1-3hrs")
        cmbReservationDuration.Items.Add("4-6hrs")
        cmbReservationDuration.Items.Add("7-11hrs")
        cmbReservationDuration.Items.Add("12+ hrs")

        cmbNumberofExpectedGuests.Items.Add("10-25")
        cmbNumberofExpectedGuests.Items.Add("26-50")
        cmbNumberofExpectedGuests.Items.Add("51-75")
        cmbNumberofExpectedGuests.Items.Add("76-100")
    End Sub

    Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
        Me.Hide()
        frmMainMenu.Show()
    End Sub
    Public Sub SetFieldsFromDataGridView(selectedRow As DataGridViewRow)
        If selectedRow IsNot Nothing Then
            txtEventName.Text = selectedRow.Cells("EventName").Value.ToString()
            dtpReservationDate.Value = selectedRow.Cells("ReservationDate").Value.ToString()
            txtTimeofReservation.Text = selectedRow.Cells("TimeofReservation").Value.ToString()
            cmbReservationDuration.SelectedItem = selectedRow.Cells("ReservationDuration").Value.ToString()
            cmbNumberofExpectedGuests.SelectedItem = selectedRow.Cells("NumberofExpectedGuests").Value.ToString()
            chkDecorations.Checked = CBool(selectedRow.Cells("Decoration").Value)
            chkCatering.Checked = CBool(selectedRow.Cells("Catering").Value)
            chkSoundandLighting.Checked = CBool(selectedRow.Cells("SoundandLightingManagement").Value)
            chkPhotoandVideo.Checked = CBool(selectedRow.Cells("PhotographerandVideographer").Value)
        End If
    End Sub


    Private Sub btnOk_Click(sender As Object, e As EventArgs) Handles btnOk.Click
        Try
            myconnection.Open()
            mycmd.Connection = myconnection
            mycmd.CommandType = CommandType.Text


            Dim enteredTime As DateTime
            If Not DateTime.TryParseExact(txtTimeofReservation.Text, "h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, enteredTime) Then
                MsgBox("Please enter a valid time in the format 'h:mm AM/PM'", MsgBoxStyle.Exclamation, "Invalid Time Format")
                Return
            End If

            mycmd.CommandText = "SELECT * FROM tblModernia WHERE EventName = '" & txtEventName.Text & "' AND ReservationDate = '" & dtpReservationDate.Value.ToString("yyyy-MM-dd") & "' AND TimeofReservation = '" & txtTimeofReservation.Text & "' AND ReservationDuration = '" & cmbReservationDuration.Text & "' AND NumberofExpectedGuests = '" & cmbNumberofExpectedGuests.Text & "'"

            dataReader = mycmd.ExecuteReader
            If dataReader.HasRows Then
                MsgBox("Event already exists", MsgBoxStyle.Exclamation, "Warning")
                dataReader.Close()
            ElseIf MessageBox.Show("Are you sure you want to add this info?", "Add", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
                dataReader.Close()

                Dim decorationsValue As Integer = If(chkDecorations.Checked, 1, 0)
                Dim cateringValue As Integer = If(chkCatering.Checked, 1, 0)
                Dim soundAndLightingValue As Integer = If(chkSoundandLighting.Checked, 1, 0)
                Dim photographerAndVideographerValue As Integer = If(chkPhotoandVideo.Checked, 1, 0)

                mycmd.CommandText = "INSERT INTO tblModernia (EventName, ReservationDate, TimeofReservation, ReservationDuration, NumberofExpectedGuests, Decoration, Catering, SoundandLightingManagement, PhotographerandVideographer) VALUES('" & txtEventName.Text.ToUpper & "','" & dtpReservationDate.Value.ToString("yyyy-MM-dd") & "', '" & txtTimeofReservation.Text.ToUpper & "', '" & cmbReservationDuration.Text.ToUpper & "', '" & cmbNumberofExpectedGuests.Text.ToUpper & "', " & decorationsValue & ", " & cateringValue & ", " & soundAndLightingValue & ", " & photographerAndVideographerValue & ")"

                mycmd.ExecuteNonQuery()
                MsgBox("Event info successfully added!", MsgBoxStyle.Information, "Information")
                Clear()
            End If
        Catch ex As Exception
            MsgBox("Error: " & ex.Message, MsgBoxStyle.Exclamation, "Error")
        Finally
            myconnection.Close()
        End Try
    End Sub
    Private Sub Clear()
        txtEventName.Clear()
        dtpReservationDate.Value = DateTime.Now
        txtTimeofReservation.Clear()
        cmbReservationDuration.SelectedIndex = -1
        cmbNumberofExpectedGuests.SelectedIndex = -1
        chkDecorations.Checked = False
        chkCatering.Checked = False
        chkSoundandLighting.Checked = False
        chkPhotoandVideo.Checked = False
    End Sub
    Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
        Me.Hide()
        frmCalendar.ShowDialog()
    End Sub

End Class

Imports MySql.Data.MySqlClient
Imports System.Globalization
Imports System.IO

Public Class frmCalendar
    Dim myconnection As MySqlConnection = New MySqlConnection("Server=localhost;Database=dbnoir;User ID=root;Password=;")
    Dim mycmd As MySqlCommand = New MySqlCommand()
    Dim dtadapter As MySqlDataAdapter = New MySqlDataAdapter()
    Dim dttbl As DataTable = New DataTable()


    Private Sub frmCalendar_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            myconnection.Open()
            mycmd.Connection = myconnection
            mycmd.CommandType = CommandType.Text
            mycmd.CommandText = "SELECT * FROM tblmodernia"
            dtadapter = New MySqlDataAdapter(mycmd)
            dttbl.Rows.Clear()
            dtadapter.Fill(dttbl)

            If Not dttbl Is Nothing AndAlso dttbl.Rows.Count > 0 Then
                DataGridView1.AutoGenerateColumns = False
                DataGridView1.DataSource = dttbl
                DataGridView1.Columns(0).DataPropertyName = "EventName"
                DataGridView1.Columns(1).DataPropertyName = "ReservationDate"
                DataGridView1.Columns(2).DataPropertyName = "TimeofReservation"
                DataGridView1.Columns(3).DataPropertyName = "ReservationDuration"
                DataGridView1.Columns(4).DataPropertyName = "NumberofExpectedGuests"
                DataGridView1.Columns(5).DataPropertyName = "Decoration"
                DataGridView1.Columns(6).DataPropertyName = "Catering"
                DataGridView1.Columns(7).DataPropertyName = "SoundandLightingManagement"
                DataGridView1.Columns(8).DataPropertyName = "PhotographerandVideographer"
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            myconnection.Close()
        End Try
    End Sub
    Private bookingForm As frmBooking

    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
        If DataGridView1.SelectedRows.Count > 0 Then
            Dim selectedRow As DataGridViewRow = DataGridView1.SelectedRows(0)
            If bookingForm Is Nothing OrElse bookingForm.IsDisposed Then
                bookingForm = New frmBooking()
            End If
            bookingForm.SetFieldsFromDataGridView(selectedRow)
            bookingForm.ShowDialog()
        Else
            MsgBox("Please select a row to update.", MsgBoxStyle.Exclamation, "No Selection")
        End If
    End Sub
End Class

该错误更集中在 frmBooking 上,特别是 SetFieldsFromDataGridView

我用新的 dgv 替换了所有内容,在数据库上重命名了我的列,遗憾的是没有任何效果,这里的期望是单击整行然后单击 btnUpdate 后,它会将我转回 frmBooking,但这次记录的所有详细信息都在刚刚添加的表单,然后按 btnOk 按钮将我恢复到 frmCalendar

database vb.net datagridview xampp
1个回答
0
投票

当我不将 SQLite DataBase 绑定到 DataGridView 时使用此代码

表单加载调用两个函数

    Private Sub frmViewTX_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    StyleDGV()
    ViewSearches()

End Sub

然后在 DGV 中设置样式并搜索并加载

Private Sub StyleDGV()

    'Set Design of the DataGridView
    dgvTX.DefaultCellStyle.Font = New Font("Times New Roman", 13.0F, FontStyle.Bold)
    dgvTX.ColumnCount = 8
    dgvTX.Columns(0).Width = 50   'ID
    dgvTX.Columns(1).Width = 140  'Date
    dgvTX.Columns(2).Width = 136  'TxType
    dgvTX.Columns(3).Width = 120  'Amt
    dgvTX.Columns(4).Width = 114  'ckNum
    dgvTX.Columns(5).Width = 390  'Desc
    dgvTX.Columns(6).Width = 130  'Bal
    dgvTX.Columns(7).Width = 10  'dumbS
    'To Set Col Header Size Mode = Enabled
    'To Set Col Header Default Cell Styles DO in Properties
    dgvTX.Columns(6).DefaultCellStyle.Format = "c"


    dgvTX.ColumnHeadersHeight = 10 'Sans Serif 'Tahoma
    dgvTX.ColumnHeadersDefaultCellStyle.Font = New Font("Sans Serif", 12.0F, FontStyle.Bold)

    dgvTX.ColumnHeadersDefaultCellStyle.ForeColor = Color.Blue
    dgvTX.DefaultCellStyle.BackColor = Color.LightGoldenrodYellow
    dgvTX.Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    dgvTX.Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
    dgvTX.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
    dgvTX.Columns(6).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight


    'dgvTX.Enabled = False 'Prevents Selection of data and scrolling
    'DGV Header Names
    dgvTX.Columns(0).Name = "TID"
    dgvTX.Columns(1).Name = "  Date"
    dgvTX.Columns(2).Name = "  Tx Type"
    dgvTX.Columns(3).Name = "  Amount"
    dgvTX.Columns(4).Name = "  CK Num"
    dgvTX.Columns(5).Name = "Desctiption"
    dgvTX.Columns(6).Name = "  Balance"
    dgvTX.Columns(7).Name = "     "


    dgvTX.Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable
    dgvTX.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
    dgvTX.Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable
    dgvTX.Columns(3).SortMode = DataGridViewColumnSortMode.NotSortable
    dgvTX.Columns(4).SortMode = DataGridViewColumnSortMode.NotSortable
    dgvTX.Columns(5).SortMode = DataGridViewColumnSortMode.NotSortable
    dgvTX.Columns(6).SortMode = DataGridViewColumnSortMode.NotSortable

End Sub

Private Sub ViewSearches()

    Dim intID As Integer
    Dim strDate As String
    Dim strTxType As String
    Dim strAmt As Decimal
    Dim strCKNum As String
    Dim strDesc As String
    Dim strBal As Decimal
    Dim rowCount As Integer
    Dim maxRowCount As Integer
    Dim emptyStr As String = "  "

    Using conn As New SQLiteConnection($"Data Source = '{gv_dbName}';Version=3;")
        conn.Open()

        Using cmd As New SQLiteCommand("", conn)

            If gvSearchType = "All" Then
                cmd.CommandText = "SELECT * FROM TxData"
            ElseIf gvSearchType = "MoRangeYr" Then
                cmd.CommandText = "SELECT * FROM TxData WHERE txSearchMonth >= $gvFromMonth AND txSearchMonth <= $gvToMonth AND txYear = $gvYear "
                'cmd.CommandText = "SELECT * FROM TxData WHERE txSearchMonth BETWEEN $gvFromMonth AND $gvToMonth AND txYear = $gvYear "
                cmd.Parameters.AddWithValue("$gvFromMonth", gvFromMonth)
                cmd.Parameters.AddWithValue("$gvToMonth", gvToMonth)
                cmd.Parameters.AddWithValue("$gvYear", gvYear)
            ElseIf gvSearchType = "MoYr" Then
                cmd.CommandText = "SELECT * FROM TxData WHERE txSearchMonth = $gvFromMonth AND txYear = $gvYear "
                cmd.Parameters.AddWithValue("$gvFromMonth", gvFromMonth)
                cmd.Parameters.AddWithValue("$gvYear", gvYear)
            ElseIf gvSearchType = "TxMoYr" Then
                cmd.CommandText = "SELECT * FROM TxData WHERE txType = $gvTxType AND txSearchMonth = $gvFromMonth AND txYear = $gvYear "
                cmd.Parameters.AddWithValue("$gvTxType", gvTxType)
                cmd.Parameters.AddWithValue("$gvFromMonth", gvFromMonth)
                cmd.Parameters.AddWithValue("$gvYear", gvYear)

            ElseIf gvSearchType = "Year" Then
                cmd.CommandText = "SELECT * FROM TxData WHERE txYear = $gvYear"
                cmd.Parameters.AddWithValue("$gvYear", gvYear)
            End If


            Using rdr As SQLite.SQLiteDataReader = cmd.ExecuteReader
                'dgvTX.DataSource = rdr
                'Statement Above is when DB is bound to dgvTX
                '============================================

                While rdr.Read()
                    intID = CInt((rdr("TID")))
                    strDate = rdr("txSortDate").ToString 'txSearchMonth '
                    strTxType = rdr("txType").ToString
                    strAmt = CDec(rdr("txAmount"))
                    strCKNum = rdr("txCKNum").ToString
                    strDesc = rdr("txDesc").ToString
                    strBal = CDec(rdr("txBalance"))
                    dgvTX.Columns(3).DefaultCellStyle.Format = "N"
                    dgvTX.Columns(6).DefaultCellStyle.Format = "N"
                    'dgvTX.Columns(6).DefaultCellStyle.Format = "C"'Adds the $ sign and commas
                    dgvTX.Rows.Add(intID, strDate, strTxType, strAmt, strCKNum, strDesc, strBal, emptyStr)

                    rowCount = rowCount + 1

                End While

                dgvTX.Columns(3).DefaultCellStyle.Format = "N"
                dgvTX.Columns(6).DefaultCellStyle.Format = "N"
                dgvTX.Sort(dgvTX.Columns(0), ListSortDirection.Descending)
            End Using

            If rowCount <= 25 Then
                maxRowCount = 25 - rowCount
                For iA = 1 To maxRowCount
                    dgvTX.Rows.Add(" ")
                Next
            End If


            lblAmt.Text = $"Current Balance  {Date.Today:MMMM d yyyy}"
            Dim dateToday = Date.Today
            Dim lblDate As String = dateToday.ToString("MMM" & " " & "d" & " " & "yyyy")
            lblAmt.Text = "Current Balance  " & lblDate

            GetCBBalance()

            tbBal.Text = "$ " & String.Format("{0:n}", strTotalBal)

        End Using
    End Using

End Sub
© www.soinside.com 2019 - 2024. All rights reserved.