0% found this document useful (0 votes)
7 views14 pages

0srms Codes

Uploaded by

Zeref Dragneel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views14 pages

0srms Codes

Uploaded by

Zeref Dragneel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

0SRMS CODES

Imports MySql.Data.MySqlClient

Imports System.Drawing.Printing

Public Class frmDashboard

' Define the MySQL connection string

Dim connectionString As String = "server=localhost; Database=osrms; username=root; password=;"

Dim connection As New MySqlConnection(connectionString)

Dim filterColumn As String = ""

Dim filterValue As String = ""

' Create PrintDocument and PrintPreviewDialog components

Private PrintDialog1 As New PrintPreviewDialog

Private dataToPrint As DataTable

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

' Initial settings on form load

txtSearchResident.Focus()

' Set default values

cmbFilterBy.SelectedIndex = 0 ' Set to "All" (assuming "All" is the first item)

cmbFilterValue.SelectedIndex = -1 ' Set to "None" or unselected

' Hide the filter value ComboBox initially

cmbFilterValue.Visible = False

' Set tab order for controls


txtSearchResident.TabIndex = 0

btnAddResident.TabIndex = 1

btnUpdateResident.TabIndex = 2

btnPrint.TabIndex = 3

btnFind.TabIndex = 4

btnReset.TabIndex = 5

btnArchiveResident.TabIndex = 6

btnReports.TabIndex = 7

btnLogOut.TabIndex = 8

' Load residents data

LoadResidents()

End Sub

' Load residents data from the database

Private Sub LoadResidents(Optional searchQuery As String = "")

Try

connection.Open()

' Define the base query

Dim query As String = "SELECT resident_number, first_name, middle_name, last_name, age,


contact_number, sector, employment_status, occupation, type_of_employment, monthly_income,
receiving_government_assistance, type_of_assistance FROM ResidentForm WHERE is_archived = 0"

' Determine filter based on ComboBox selection

If cmbFilterBy.SelectedItem IsNot Nothing Then

Select Case cmbFilterBy.SelectedItem.ToString()

Case "Sector"

filterColumn = "sector"

If cmbFilterValue.SelectedItem IsNot Nothing Then


filterValue = cmbFilterValue.SelectedItem.ToString()

End If

Case "Employment Status"

filterColumn = "employment_status"

If cmbFilterValue.SelectedItem IsNot Nothing Then

filterValue = cmbFilterValue.SelectedItem.ToString()

End If

Case "Type of Assistance"

filterColumn = "type_of_assistance"

If cmbFilterValue.SelectedItem IsNot Nothing Then

filterValue = cmbFilterValue.SelectedItem.ToString()

End If

Case "All"

' No filter logic needed when "All" is selected

filterColumn = ""

End Select

End If

' Modify the query if there is a search input and filter option selected

If Not String.IsNullOrEmpty(searchQuery) Then

query &= " AND (first_name LIKE @search OR last_name LIKE @search OR resident_number
LIKE @search)"

End If

' Apply additional filter by the selected value if needed

If Not String.IsNullOrEmpty(filterColumn) AndAlso Not String.IsNullOrEmpty(filterValue) Then

query &= " AND " & filterColumn & " = @filterValue"

End If
' Create the command with the query and parameters

Dim cmd As New MySqlCommand(query, connection)

' Add parameters for search and filter value

If Not String.IsNullOrEmpty(searchQuery) Then

cmd.Parameters.AddWithValue("@search", "%" & searchQuery & "%")

End If

If Not String.IsNullOrEmpty(filterValue) Then

cmd.Parameters.AddWithValue("@filterValue", filterValue)

End If

' Execute the query and fill the data into the DataGridView

Dim adapter As New MySqlDataAdapter(cmd)

Dim table As New DataTable()

adapter.Fill(table)

dataToPrint = table ' Store data for printing

' Bind the DataTable to the DataGridView

dgvResidents.DataSource = table

' Set column headers

dgvResidents.Columns("resident_number").HeaderText = "Resident Number"

dgvResidents.Columns("first_name").HeaderText = "First Name"

dgvResidents.Columns("middle_name").HeaderText = "Middle Name"

dgvResidents.Columns("last_name").HeaderText = "Last Name"

dgvResidents.Columns("age").HeaderText = "Age"

dgvResidents.Columns("contact_number").HeaderText = "Contact Number"

dgvResidents.Columns("sector").HeaderText = "Sector"

dgvResidents.Columns("employment_status").HeaderText = "Employment Status"


dgvResidents.Columns("occupation").HeaderText = "Occupation"

dgvResidents.Columns("type_of_employment").HeaderText = "Type of Employment"

dgvResidents.Columns("monthly_income").HeaderText = "Monthly Income"

dgvResidents.Columns("receiving_government_assistance").HeaderText = "Receiving Assistance"

dgvResidents.Columns("type_of_assistance").HeaderText = "Type of Assistance"

Catch ex As Exception

MessageBox.Show("Error loading data: " & ex.Message, "Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

Finally

connection.Close()

End Try

End Sub

' Search button click event

Private Sub btnFind_Click(sender As Object, e As EventArgs) Handles btnFind.Click

LoadResidents(txtSearchResident.Text.Trim())

End Sub

' KeyPress event for pressing Enter in txtSearchResident

Private Sub txtSearchResident_KeyPress(sender As Object, e As KeyPressEventArgs) Handles


txtSearchResident.KeyPress

If e.KeyChar = ChrW(Keys.Enter) Then

LoadResidents(txtSearchResident.Text.Trim())

e.Handled = True

End If

End Sub

Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click

' Set the page to landscape

PrintDocument1.DefaultPageSettings.Landscape = True
' Maximize the PrintPreviewDialog window

PrintDialog1.WindowState = FormWindowState.Maximized

' Set custom paper size to Short Bond (8.5 x 13 inches)

Dim shortBondSize As New Printing.PaperSize("Short Bond", 850, 1300) ' 850 and 1300 are in
hundredths of an inch (8.5 x 13 inches)

PrintDocument1.DefaultPageSettings.PaperSize = shortBondSize

' Show the print dialog

PrintDialog1.Document = PrintDocument1

PrintDialog1.ShowDialog()

End Sub

' Variables to keep track of the printing state

Private currentPageIndex As Integer = 0

Private totalRowsPrinted As Integer = 0

Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles


PrintDocument1.PrintPage

' Define fonts for different sections

Dim font As New Font("Arial", 8) ' For data rows

Dim fontHeader As New Font("Arial", 9, FontStyle.Bold) ' For column headers

Dim fontTitle As New Font("Arial", 16, FontStyle.Bold) ' Larger font for the title

' Define printing area without margins

Dim availableWidth As Integer = e.PageBounds.Width

Dim availableHeight As Integer = e.PageBounds.Height

Dim startX As Integer = 0

Dim startY As Integer = 0


Dim offset As Integer = 40

' Define the report title

Dim reportTitle As String = "Residents Data"

' Define the margin from the top of the page

Dim topMargin As Integer = 40 ' Adjust this value for more or less space from the top

' Center the title horizontally and apply the top margin

Dim titleWidth As Integer = TextRenderer.MeasureText(reportTitle, fontTitle).Width

Dim titleHeight As Integer = TextRenderer.MeasureText(reportTitle, fontTitle).Height

Dim centerX As Integer = (availableWidth - titleWidth) / 2

Dim titleYPosition As Integer = topMargin ' Set Y position with top margin

e.Graphics.DrawString(reportTitle, fontTitle, Brushes.Black, centerX, titleYPosition)

' Adjust the start position for data to be below the title with additional spacing

startY = titleYPosition + titleHeight + 5

' Calculate maximum width for each column based on data and headers

Dim columnWidths As New List(Of Integer)()

For i As Integer = 0 To dgvResidents.Columns.Count - 1

Dim maxColumnWidth As Integer =


TextRenderer.MeasureText(dgvResidents.Columns(i).HeaderText, fontHeader).Width

For Each row As DataGridViewRow In dgvResidents.Rows

If Not row.IsNewRow Then

Dim cellText As String = row.Cells(i).FormattedValue.ToString()

maxColumnWidth = Math.Max(maxColumnWidth, TextRenderer.MeasureText(cellText,


font).Width)

End If
Next

columnWidths.Add(maxColumnWidth)

Next

' Scale column widths to fit the available print width

Dim totalWidth As Integer = columnWidths.Sum()

Dim scaleFactor As Double = availableWidth / totalWidth

' Print column headers with scaling, borders, and center alignment

Dim currentX As Integer = startX

For i As Integer = 0 To dgvResidents.Columns.Count - 1

Dim scaledColumnWidth As Integer = CInt(columnWidths(i) * scaleFactor)

Dim headerText As String = dgvResidents.Columns(i).HeaderText

Dim headerTextWidth As Integer = TextRenderer.MeasureText(headerText, fontHeader).Width

Dim headerTextX As Integer = currentX + (scaledColumnWidth - headerTextWidth) / 2

e.Graphics.DrawString(headerText, fontHeader, Brushes.Black, headerTextX, startY + offset)

e.Graphics.DrawRectangle(Pens.Black, currentX, startY + offset, scaledColumnWidth, 20)

currentX += scaledColumnWidth

Next

offset += 20

currentX = startX

' Print data rows with scaling, borders, and center alignment

Dim rowsPrinted As Integer = 0

Dim maxRowsPerPage As Integer = 30

For i As Integer = totalRowsPrinted To dgvResidents.Rows.Count - 1

If dgvResidents.Rows(i).IsNewRow Then Continue For


' Limit the number of rows per page

If rowsPrinted >= maxRowsPerPage Then

e.HasMorePages = True

currentPageIndex += 1

Return

End If

' Print each column in the current row

For j As Integer = 0 To dgvResidents.Columns.Count - 1

Dim scaledColumnWidth As Integer = CInt(columnWidths(j) * scaleFactor)

Dim cellText As String = dgvResidents.Rows(i).Cells(j).FormattedValue.ToString()

Dim cellTextWidth As Integer = TextRenderer.MeasureText(cellText, font).Width

Dim cellTextX As Integer = currentX + (scaledColumnWidth - cellTextWidth) / 2

e.Graphics.DrawString(cellText, font, Brushes.Black, cellTextX, startY + offset)

e.Graphics.DrawRectangle(Pens.Black, currentX, startY + offset, scaledColumnWidth,


CInt(dgvResidents.RowTemplate.Height))

currentX += scaledColumnWidth

Next

offset += CInt(dgvResidents.RowTemplate.Height)

currentX = startX

rowsPrinted += 1

totalRowsPrinted += 1

' Check if we reached the end of the printable area

If offset >= availableHeight Then

e.HasMorePages = True

currentPageIndex += 1

Return
End If

Next

' Reset page control variables after printing is complete

e.HasMorePages = False

currentPageIndex = 0

totalRowsPrinted = 0

End Sub

' Add Resident button click event

Private Sub btnAddResident_Click(sender As Object, e As EventArgs) Handles btnAddResident.Click

frmAddResident.Show()

Me.Close()

End Sub

' Update Resident button click event

Private Sub btnUpdateResident_Click(sender As Object, e As EventArgs) Handles


btnUpdateResident.Click

frmUpdateResident.Show()

Me.Close()

End Sub

' Archive Resident button click event

Private Sub btnArchiveResident_Click(sender As Object, e As EventArgs) Handles


btnArchiveResident.Click

frmArchiveResident.Show()

Me.Close()

End Sub

' Reports button click event


Private Sub btnReports_Click(sender As Object, e As EventArgs) Handles btnReports.Click

frmReports.Show()

Me.Close()

End Sub

' Reset button click event

Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click

' Clear the search text box

txtSearchResident.Clear()

' Reset the filter ComboBox (cmbFilterBy) to its default state

cmbFilterBy.SelectedIndex = 0 ' Set to "All" (assuming "All" is the first item)

' Reset the filter value ComboBox (cmbFilterValue) to its default state

cmbFilterValue.Items.Clear() ' Remove any values in cmbFilterValue

cmbFilterValue.SelectedIndex = -1 ' Set to "None" or unselected

' Hide the cmbFilterValue as no filter is selected

cmbFilterValue.Visible = False

' Reload all the residents without any filters

LoadResidents()

txtSearchResident.Focus()

End Sub

' Log Out button click event

Private Sub btnLogOut_Click(sender As Object, e As EventArgs) Handles btnLogOut.Click

frmLogin.Show()

Me.Close()

End Sub
' ComboBox for FilterBy selected index change

Private Sub cmbFilterBy_SelectedIndexChanged(sender As Object, e As EventArgs) Handles


cmbFilterBy.SelectedIndexChanged

' Clear previous items in the second ComboBox

cmbFilterValue.Items.Clear()

' Ensure cmbFilterBy has a selected item before processing

If cmbFilterBy.SelectedItem IsNot Nothing Then

Select Case cmbFilterBy.SelectedItem.ToString()

Case "Sector"

' Update sector options to values from 1 to 7

For i As Integer = 1 To 7

cmbFilterValue.Items.Add(i.ToString())

Next

Case "Employment Status"

cmbFilterValue.Items.Add("Employed")

cmbFilterValue.Items.Add("Unemployed")

cmbFilterValue.Items.Add("Self-Employed")

cmbFilterValue.Items.Add("Retired")

cmbFilterValue.Items.Add("Student")

' Add other employment status options

Case "Type of Assistance"

cmbFilterValue.Items.Add("4P's")

cmbFilterValue.Items.Add("Pension")

' Add other assistance types

Case "All" ' If "All" is selected, hide the filter value ComboBox

cmbFilterValue.Visible = False

Exit Sub

End Select
' Show the cmbFilterValue and enable it

cmbFilterValue.Visible = True

If cmbFilterValue.Items.Count > 0 Then

cmbFilterValue.SelectedIndex = 0

End If

Else

' If no selection in cmbFilterBy, hide the cmbFilterValue

cmbFilterValue.Visible = False

End If

End Sub

Private Sub ResetFilters()

' Clear the search input field

txtSearchResident.Clear()

' Reset the ComboBox filter selection (clear it, set to default)

cmbFilterBy.SelectedIndex = -1 ' No selection

' Clear the filter values in cmbFilterValue

cmbFilterValue.Items.Clear()

cmbFilterValue.SelectedIndex = -1 ' Set to null by clearing the selection

cmbFilterValue.Enabled = False ' Disable the filter value ComboBox

' Optionally, reset the DataGridView if needed

dgvResidents.DataSource = Nothing

dgvResidents.Rows.Clear()

' Reload the data (optional) to reset the grid view without any filter

LoadResidents()
End Sub

Private Sub cmbFilterValue_KeyPress(sender As Object, e As KeyPressEventArgs) Handles


cmbFilterValue.KeyPress

' Check if Enter key is pressed

If e.KeyChar = ChrW(Keys.Enter) Then

' Trigger search based on the selected filter and value

If cmbFilterBy.SelectedItem IsNot Nothing AndAlso cmbFilterValue.SelectedItem IsNot Nothing


Then

LoadResidents(txtSearchResident.Text.Trim()) ' Call search with current text

Else

MessageBox.Show("Please select a valid filter and value.", "Error", MessageBoxButtons.OK,


MessageBoxIcon.Error)

End If

e.Handled = True ' Mark event as handled so no further processing happens

End If

End Sub

Private Sub btnResidents_Click(sender As Object, e As EventArgs) Handles btnResidents.Click

End Sub

End Class

You might also like