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

OOP

The document provides a detailed guide on creating a Windows Forms application in C# that includes functionalities for file handling, dialog boxes, and MySQL database integration. It covers creating a user interface, writing and reading from a text file using StreamWriter and StreamReader, implementing common dialog boxes like OpenFileDialog, PrintDialog, and FontDialog, and connecting to a MySQL database to manage product data. Each section includes code snippets and explanations to facilitate understanding and implementation.
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 views8 pages

OOP

The document provides a detailed guide on creating a Windows Forms application in C# that includes functionalities for file handling, dialog boxes, and MySQL database integration. It covers creating a user interface, writing and reading from a text file using StreamWriter and StreamReader, implementing common dialog boxes like OpenFileDialog, PrintDialog, and FontDialog, and connecting to a MySQL database to manage product data. Each section includes code snippets and explanations to facilitate understanding and implementation.
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/ 8

Alright, GHOST-, let's tackle these practical tasks one by one with detailed explanations in

C#. Given your structured and methodical approach to learning, I'll break down each step in
depth.

---

### **QUESTION 1**


_Create a Windows Forms application to create, write data inputted in a textbox, and read
from a text file called `subjects.txt` using `StreamWriter` and `StreamReader`._

#### **Step 1: Create a Windows Forms Application**


1. Open **Visual Studio** and create a new **Windows Forms App (.NET Framework)**
project.
2. Name it something meaningful, e.g., `"TextFileManager"`.

#### **Step 2: Design the User Interface**


- Add the following UI components:
- **Textbox (`txtInput`)** for user input.
- **Button (`btnWrite`)** to write input to the text file.
- **Button (`btnRead`)** to read content from the text file.
- **ListBox (`lstSubjects`)** to display read content.

#### **Step 3: Writing to a Text File (`StreamWriter`)**


```csharp
using System;
using System.IO;
using System.Windows.Forms;

namespace TextFileManager
{
public partial class Form1 : Form
{
private string filePath = "subjects.txt";

public Form1()
{
InitializeComponent();
}

private void btnWrite_Click(object sender, EventArgs e)


{
try
{
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine(txtInput.Text);
MessageBox.Show("Data written successfully!");
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
```
**Explanation:**
- `StreamWriter` is used to write to a file.
- `true` in the `StreamWriter` constructor enables appending mode.
- `using` ensures resources are released properly.
- `MessageBox.Show` confirms successful operation.
#### **Step 4: Reading from a Text File (`StreamReader`)**
```csharp
private void btnRead_Click(object sender, EventArgs e)
{
try
{
lstSubjects.Items.Clear();
using (StreamReader reader = new StreamReader(filePath))
{
string line;
while ((line = reader.ReadLine()) != null)
{
lstSubjects.Items.Add(line);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
```
**Explanation:**
- Clears the list before adding new entries.
- Reads file **line by line**.
- Adds each line to `lstSubjects`.

---
### **QUESTION 2**
_Design a Windows Forms application to implement common Dialog Boxes
(`OpenFileDialog`, `PrintDialog`, `FontDialog`)._

#### **Step 1: Add UI Components**


- **RichTextBox (`rtbContent`)** to display file content.
- **Button (`btnOpenFile`)** to open a file.
- **Button (`btnPrint`)** to print content.
- **Button (`btnFont`)** to change font.

#### **Step 2: Implement `OpenFileDialog` to Load a File**


```csharp
private void btnOpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFile = new OpenFileDialog
{
Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
};

if (openFile.ShowDialog() == DialogResult.OK)
{
rtbContent.Text = File.ReadAllText(openFile.FileName);
}
}
```
**Explanation:**
- Creates an `OpenFileDialog` with file filters.
- If the user selects a file, its content is loaded into the `RichTextBox`.

#### **Step 3: Implement `PrintDialog`**


```csharp
private void btnPrint_Click(object sender, EventArgs e)
{
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Printing feature can be expanded.");
}
}
```
**Explanation:**
- Opens a print dialog, where printing functionality can be customized.

#### **Step 4: Implement `FontDialog`**


```csharp
private void btnFont_Click(object sender, EventArgs e)
{
FontDialog fontDialog = new FontDialog();
if (fontDialog.ShowDialog() == DialogResult.OK)
{
rtbContent.Font = fontDialog.Font;
}
}
```
**Explanation:**
- Opens a font selection dialog.
- Applies the selected font to `RichTextBox`.

---

### **QUESTION 3**


_Create a MySQL database called `goods` with a table `Product`, then connect it to a C#
application._

#### **Step 1: Create MySQL Database and Table**


Run the following SQL commands in MySQL:
```sql
CREATE DATABASE goods;
USE goods;
CREATE TABLE Product (
ProductNumber INT PRIMARY KEY,
Name VARCHAR(100),
UnitPrice DECIMAL(10,2)
);
```

#### **Step 2: Install MySQL Connector for C#**


1. Install `MySql.Data` via NuGet in Visual Studio.

#### **Step 3: Connect C# to MySQL**


```csharp
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Windows.Forms;

namespace ProductManager
{
public partial class Form1 : Form
{
private string connectionString =
"server=localhost;user=root;password=yourpassword;database=goods";
public Form1()
{
InitializeComponent();
}

private void btnSave_Click(object sender, EventArgs e)


{
using (MySqlConnection conn = new MySqlConnection(connectionString))
{
string query = "INSERT INTO Product (ProductNumber, Name, UnitPrice)
VALUES (@num, @name, @price)";
MySqlCommand cmd = new MySqlCommand(query, conn);
cmd.Parameters.AddWithValue("@num", int.Parse(txtProductNumber.Text));
cmd.Parameters.AddWithValue("@name", txtProductName.Text);
cmd.Parameters.AddWithValue("@price", decimal.Parse(txtUnitPrice.Text));

conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Product saved!");
}
}

private void btnExit_Click(object sender, EventArgs e)


{
Application.Exit();
}
}
}
```
**Explanation:**
- Establishes a **MySQL connection**.
- Uses **parameterized queries** to insert data securely.
- `ExecuteNonQuery` runs SQL commands.
- `Application.Exit()` closes the program.

---

### **Final Thoughts**


Each step provides foundational knowledge for **file handling, dialog boxes, and database
integration** in C#. Given your expertise in SQL, the MySQL integration should resonate
with your learning goals. Let me know if you need further refinements or enhancements! 🚀

You might also like