In Visual Basic: Create an application that allows library staff to enter data for each book, including Title, Year, Author and Availability, into a digital system. The data should be stored in an array and displayed in a ListView component for easy viewing and quick access. The "Available" field should be filled in using two RadioButtons (Yes/No), which store a Boolean value (true/false) depending on the user's choice. In addition, the program should validate all entries, ensuring that no mandatory fields are left blank.
Template code:
Public Class Form1
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
code
End Sub
Private Sub lbl_titulo_Click(sender As Object, e As EventArgs) Handles lbl_titulo.Click
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Marcar o Não por padrão
rbt_nao.Checked = True
End Sub
Private Sub btn_cadastrar_Click(sender As Object, e As EventArgs) Handles btn_cadastrar.Click
' Entrada dos dados
Dim titulo As Object = txt_title.Text
Dim ano As Short
Dim autor As String = txt_author.Text
Dim disp As Boolean = IIf(rbt_sim.Checked, True, False
Dim mensage As String = ""
' Trying to implement a local database using listView
Dim Item As ListViewItem
' Input validation
If String.IsNullOrWhiteSpace(txt_title.Text) Then
MessageBox.Show("Por favor informe o nome do livro.", "Erro de validação", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_title.Focus()
Exit Sub
End If
If Short.TryParse(txt_Year.Text, ano) Then
' Successfully parsed, proceed with ano
' Here, 'ano' has the parsed value
Else
' Parsing failed, notify user
MessageBox.Show("Por favor, insira um número válido para o ano.", "Valor Inválido", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_Year.Focus()
txt_Year.SelectAll()
' Optionally, reset ano to a default value or handle this case
ano = 0 ' or any default year
End If
End Sub
Assistant
End Class
Certainly! Below is a complete example of a Visual Basic (VB.NET) Windows Forms application that allows library staff to enter data for each book, store it in an array, and display it in a ListView control. The application includes validation to ensure mandatory fields are not left blank and uses RadioButtons to capture the availability of each book.
Overview
User Interface Components:
TextBoxes:
txt_title for the book title
txt_Year for the publication year
txt_author for the author's name
RadioButtons:
rbt_sim (Yes) for availability
rbt_nao (No) for availability
Button:
btn_cadastrar to add/register the book
ListView:
ListView1 to display the list of books
Functionality:
Data Entry: Users can input the Title, Year, and Author of a book.
Availability: Users can select whether the book is available using RadioButtons.
Data Storage: The entered data is stored in an array.
Display: The array data is displayed in the ListView for easy viewing.
Validation: Ensures that no mandatory fields are left blank and that the Year is a valid number.
Step-by-Step Implementation
1. Define the Book Class
First, create a Book class to represent each book's data.
vb
Public Class Book
Public Property Title As String
Public Property Year As Integer
Public Property Author As String
Public Property Availability As Boolean
Public Sub New(title As String, year As Integer, author As String, availability As Boolean)
Me.Title = title
Me.Year = year
Me.Author = author
Me.Availability = availability
End Sub
End Class
2. Design the User Interface
Ensure your form (Form1) includes the following controls:
TextBoxes:
txt_title: For entering the book title.
txt_author: For entering the author's name.
txt_Year: For entering the publication year.
RadioButtons:
rbt_sim: Represents "Yes" for availability.
rbt_nao: Represents "No" for availability.
Button:
btn_cadastrar: When clicked, it will add the book to the ListView.
ListView:
ListView1: To display the list of books. Set its View property to Details.
Labels:
Appropriate labels for each TextBox and RadioButton.
3. Implement the Form Code
Below is the complete code for Form1, incorporating the required functionality.
vb
4. Explanation of the Code
Book Class:
Represents each book with properties: Title, Year, Author, and Availability.
The constructor initializes these properties.
Books Array:
An array named books is initialized with an initial capacity (initialCapacity), set to 10.
bookCount keeps track of the number of books added.
The AddBook method manages adding a new book to the array, resizing it when necessary using ReDim Preserve.
Form Load (Form1_Load):
Sets the default RadioButton (rbt_nao) for availability to "No."
Configures the ListView1 with details view, full row selection, and grid lines.
Adds columns to the ListView for Title, Year, Author, and Available status.
Button Click (btn_cadastrar_Click):
Validates user input for Title, Author, and Year.
If validation passes, creates a new Book object with the entered data.
Adds the new book to the books array using the AddBook method.
Creates a new ListViewItem with the book's data and adds it to ListView1.
Clears the input fields for the next entry and shows a success message.
Adding Books to Array:
The AddBook method checks if the current array has enough space.
If not, it resizes the array by doubling its current length.
Adds the new book to the array and increments the bookCount.
Clearing Input Fields:
The ClearInputFields method resets all input fields and sets the availability RadioButton back to "No."
Additional Event Handlers:
ListView1_SelectedIndexChanged and lbl_titulo_Click are included as placeholders for any future functionality you might want to add, such as editing or deleting entries.
5. Running the Application
Initialization:
When the application starts, Form1_Load initializes the ListView and sets the default state of the RadioButtons.
Adding a Book:
The user enters the Title, Year, and Author of a book.
The user selects the availability using the RadioButtons.
Upon clicking the "Cadastrar" button:
The application validates the inputs.
If valid, the book is added to the books array and displayed in the ListView.
Input fields are cleared for the next entry.
Viewing Books:
All added books are visible in ListView1 with their respective details.
6. Considerations and Enhancements
Using Lists Instead of Arrays:
While this implementation uses dynamic arrays with manual resizing, using a List(Of Book) is more efficient and easier to manage in VB.NET.
A List automatically handles resizing, making the code cleaner and more maintainable.
Data Persistence:
Currently, the data exists only during the application's runtime. To persist data between sessions, consider saving the books array or List to a file or a database.
Editing and Deleting Entries:
Implement functionality to edit or delete existing books from the ListView and the underlying array or list.
Enhanced Validation:
Add more robust validation, such as checking for duplicate titles or ensuring the year is within a realistic range.
User Feedback:
Implement additional user feedback mechanisms, such as highlighting mandatory fields or providing success animations.
7. Recommended Code with List Instead of Array
For better efficiency and code simplicity, consider using a List(Of Book) instead of an array. Here's how you can modify the code accordingly:
vb
Advantages of Using List(Of Book):
Dynamic Sizing: Automatically handles the addition of new items without manual resizing.
Simpler Code: Eliminates the need for managing array indexes and resizing.
Built-in Methods: Provides methods like Add, Remove, and Find for easier management.
Conclusion
This implementation provides a robust foundation for managing library books within a VB.NET Windows Forms application. It ensures data integrity through validation, offers an easy-to-use interface for staff, and presents the data in a clear and organized ListView. By following this guide, you can further expand the application to include more features such as editing, deleting, and persisting data to a database or file system.
Feel free to reach out if you need further assistance or enhancements!
Not yet included in a published release.
Public Class Form1
' Define the Book class
Public Class Book
Public Property Title As String
Public Property Year As Integer
Public Property Author As String
Public Property Availability As Boolean
Public Sub New(title As String, year As Integer, author As String, availability As Boolean)
Me.Title = title
Me.Year = year
Me.Author = author
Me.Availability = availability
End Sub
End Class
' Initialize an array to store books
Private books() As Book
Private bookCount As Integer = 0
Private Const initialCapacity As Integer = 10
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Initialize the books array with initial capacity
ReDim books(initialCapacity - 1)
' Set default RadioButton selection to 'No'
rbt_nao.Checked = True
' Initialize ListView properties
ListView1.View = View.Details
ListView1.FullRowSelect = True
ListView1.GridLines = True
' Add columns to ListView
ListView1.Columns.Add("Title", 200, HorizontalAlignment.Left)
ListView1.Columns.Add("Year", 70, HorizontalAlignment.Left)
ListView1.Columns.Add("Author", 150, HorizontalAlignment.Left)
ListView1.Columns.Add("Available", 80, HorizontalAlignment.Left)
End Sub
Private Sub btn_cadastrar_Click(sender As Object, e As EventArgs) Handles btn_cadastrar.Click
' Input Validation
If String.IsNullOrWhiteSpace(txt_title.Text) Then
MessageBox.Show("Please enter the book title.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_title.Focus()
Exit Sub
End If
If String.IsNullOrWhiteSpace(txt_author.Text) Then
MessageBox.Show("Please enter the author's name.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_author.Focus()
Exit Sub
End If
Dim year As Integer
If Not Integer.TryParse(txt_Year.Text, year) Then
MessageBox.Show("Please enter a valid year.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_Year.Focus()
txt_Year.SelectAll()
Exit Sub
End If
' Determine availability from RadioButtons
Dim isAvailable As Boolean = rbt_sim.Checked
' Create a new Book object
Dim newBook As New Book(txt_title.Text.Trim(), year, txt_author.Text.Trim(), isAvailable)
' Add the new book to the array
AddBook(newBook)
' Add the new book to the ListView
Dim listItem As New ListViewItem(newBook.Title)
listItem.SubItems.Add(newBook.Year.ToString())
listItem.SubItems.Add(newBook.Author)
listItem.SubItems.Add(If(newBook.Availability, "Yes", "No"))
ListView1.Items.Add(listItem)
' Optionally, clear the input fields after adding
ClearInputFields()
MessageBox.Show("Book added successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
' Method to add a book to the array, resizing if necessary
Private Sub AddBook(newBook As Book)
If bookCount >= books.Length Then
' Resize the array by doubling its size
ReDim Preserve books(books.Length * 2 - 1)
End If
books(bookCount) = newBook
bookCount += 1
End Sub
' Method to clear input fields
Private Sub ClearInputFields()
txt_title.Clear()
txt_author.Clear()
txt_Year.Clear()
rbt_nao.Checked = True ' Reset to 'No' by default
End Sub
' Optional: Handle ListView selection change if needed
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
' You can implement selection change logic here if needed
End Sub
' Optional: Handle any other events as needed
Private Sub lbl_titulo_Click(sender As Object, e As EventArgs) Handles lbl_titulo.Click
' Implement label click logic if required
End Sub
End Class
Public Class Form1
' Define the Book class
Public Class Book
Public Property Title As String
Public Property Year As Integer
Public Property Author As String
Public Property Availability As Boolean
Public Sub New(title As String, year As Integer, author As String, availability As Boolean)
Me.Title = title
Me.Year = year
Me.Author = author
Me.Availability = availability
End Sub
End Class
' Initialize a List to store books
Private books As New List(Of Book)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set default RadioButton selection to 'No'
rbt_nao.Checked = True
' Initialize ListView properties
ListView1.View = View.Details
ListView1.FullRowSelect = True
ListView1.GridLines = True
' Add columns to ListView
ListView1.Columns.Add("Title", 200, HorizontalAlignment.Left)
ListView1.Columns.Add("Year", 70, HorizontalAlignment.Left)
ListView1.Columns.Add("Author", 150, HorizontalAlignment.Left)
ListView1.Columns.Add("Available", 80, HorizontalAlignment.Left)
End Sub
Private Sub btn_cadastrar_Click(sender As Object, e As EventArgs) Handles btn_cadastrar.Click
' Input Validation
If String.IsNullOrWhiteSpace(txt_title.Text) Then
MessageBox.Show("Please enter the book title.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_title.Focus()
Exit Sub
End If
If String.IsNullOrWhiteSpace(txt_author.Text) Then
MessageBox.Show("Please enter the author's name.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_author.Focus()
Exit Sub
End If
Dim year As Integer
If Not Integer.TryParse(txt_Year.Text, year) Then
MessageBox.Show("Please enter a valid year.", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
txt_Year.Focus()
txt_Year.SelectAll()
Exit Sub
End If
' Determine availability from RadioButtons
Dim isAvailable As Boolean = rbt_sim.Checked
' Create a new Book object
Dim newBook As New Book(txt_title.Text.Trim(), year, txt_author.Text.Trim(), isAvailable)
' Add the new book to the list
books.Add(newBook)
' Add the new book to the ListView
Dim listItem As New ListViewItem(newBook.Title)
listItem.SubItems.Add(newBook.Year.ToString())
listItem.SubItems.Add(newBook.Author)
listItem.SubItems.Add(If(newBook.Availability, "Yes", "No"))
ListView1.Items.Add(listItem)
' Optionally, clear the input fields after adding
ClearInputFields()
MessageBox.Show("Book added successfully.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Sub
' Method to clear input fields
Private Sub ClearInputFields()
txt_title.Clear()
txt_author.Clear()
txt_Year.Clear()
rbt_nao.Checked = True ' Reset to 'No' by default
End Sub
' Optional: Handle ListView selection change if needed
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
' You can implement selection change logic here if needed
End Sub
' Optional: Handle any other events as needed
Private Sub lbl_titulo_Click(sender As Object, e As EventArgs) Handles lbl_titulo.Click
' Implement label click logic if required
End Sub
End Class