-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateStudentReportForm.cs
More file actions
104 lines (93 loc) · 3.34 KB
/
GenerateStudentReportForm.cs
File metadata and controls
104 lines (93 loc) · 3.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Windows.Forms;
using System.IO;
using OfficeOpenXml;
namespace TinyCollegeGUI
{
public partial class GenerateStudentReportForm : Form
{
private string connectionString;
public GenerateStudentReportForm()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["TinyCollegeDB"].ConnectionString;
}
private void GenerateStudentReportForm_Load(object sender, EventArgs e)
{
// Any initialization tasks can be performed here.
}
private void btnGenerateReport_Click(object sender, EventArgs e)
{
var criteria = txtCriteria.Text;
var dataTable = GetStudentReportData(criteria);
if (dataTable.Rows.Count > 0)
{
SaveReport(dataTable);
}
else
{
MessageBox.Show("No data found for the given criteria.");
}
}
private DataTable GetStudentReportData(string criteria)
{
var dataTable = new DataTable();
using (var connection = new SqlConnection(connectionString))
{
string query = "SELECT * FROM Students WHERE FirstName LIKE @Criteria OR LastName LIKE @Criteria";
using (var command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Criteria", $"%{criteria}%");
using (var adapter = new SqlDataAdapter(command))
{
adapter.Fill(dataTable);
}
}
}
return dataTable;
}
private void SaveReport(DataTable dataTable)
{
var saveFileDialog = new SaveFileDialog
{
Filter = "Excel Files|*.xlsx|PDF Files|*.pdf",
Title = "Save Report"
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
var filePath = saveFileDialog.FileName;
var fileExtension = Path.GetExtension(filePath);
switch (fileExtension)
{
case ".xlsx":
ExportToExcel(dataTable, filePath);
break;
default:
MessageBox.Show("Unsupported file format.");
break;
}
}
}
private void ExportToExcel(DataTable dataTable, string filePath)
{
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Student Report");
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
package.SaveAs(new FileInfo(filePath));
}
MessageBox.Show("Report exported to Excel successfully.");
}
// Couldnt get the PDF to work. :(
/* private void ExportToPdf(DataTable dataTable, string filePath)
{
MessageBox.Show("PDF export functionality to be implemented.");
}
*/
}
}