This repository has been archived by the owner on Dec 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtileria.cs
242 lines (207 loc) · 8.59 KB
/
Utileria.cs
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Data.SqlClient;
namespace ShowTime_DatabseProject
{
public partial class Utileria : Form
{
// Cadena de conexión obtenida desde el archivo de configuración
private readonly string sqlServerConnectionString = ConfigurationManager.ConnectionStrings["connection_S"].ConnectionString;
public Utileria()
{
InitializeComponent();
InitializeCustomComponents();
}
/// <summary>
/// Configura los componentes iniciales y sus eventos.
/// </summary>
private void InitializeCustomComponents()
{
// Cargar datos iniciales en el DataGridView
LoadDataToDataGridView();
// Configurar estilos personalizados en botones
Utils.AgregarBordeInferiorConHover(btnRegisterProp, Color.FromArgb(18, 29, 36), 3, Color.FromArgb(10, 180, 180, 180), Color.Black);
Utils.AgregarBordeInferiorConHover(btnUpdateUtileria, Color.FromArgb(18, 29, 36), 3, Color.FromArgb(10, 180, 180, 180), Color.Black);
// Desactivar botones hasta que se valide la entrada
btnRegisterProp.Enabled = false;
btnUpdateUtileria.Enabled = false;
// Agregar validación dinámica de entradas de texto
txtPropName.TextChanged += ValidateInputs;
numCantidad.TextChanged += ValidateInputs;
}
/// <summary>
/// Valida los campos de entrada y habilita/deshabilita los botones según corresponda.
/// </summary>
private void ValidateInputs(object sender, EventArgs e)
{
bool isNameValid = !string.IsNullOrWhiteSpace(txtPropName.Text);
bool isQuantityValid = int.TryParse(numCantidad.Text, out _);
// Habilitar botones solo si los datos son válidos
btnRegisterProp.Enabled = isNameValid && isQuantityValid;
btnUpdateUtileria.Enabled = dgvUtileria.SelectedRows.Count > 0 && isNameValid && isQuantityValid;
}
/// <summary>
/// Obtiene todas las utilerías desde la base de datos.
/// </summary>
/// <returns>Lista de objetos Utileria.</returns>
public IEnumerable<Models.Utileria> GetAll()
{
List<Models.Utileria> utilerias = new List<Models.Utileria>();
try
{
using (SqlConnection connection = new SqlConnection(sqlServerConnectionString))
{
connection.Open();
string query = "SELECT * FROM Utileria";
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
utilerias.Add(new Models.Utileria
{
IdUtileria = Convert.ToInt32(reader["Id_utileria"]),
Nombre = reader["Nombre"].ToString(),
Cantidad = Convert.ToInt32(reader["Cantidad"])
});
}
}
}
}
catch (Exception ex)
{
ShowErrorMessage("Error al obtener las utilerías", ex);
}
return utilerias;
}
/// <summary>
/// Carga los datos de utilería en el DataGridView.
/// </summary>
private void LoadDataToDataGridView()
{
try
{
dgvUtileria.DataSource = GetAll().ToList();
if (dgvUtileria.Columns["IdUtileria"] != null)
dgvUtileria.Columns["IdUtileria"].Visible = false;
if (dgvUtileria.Columns["ServicioUtileria"] != null)
dgvUtileria.Columns["ServicioUtileria"].Visible = false;
}
catch (Exception ex)
{
ShowErrorMessage("Error al cargar los datos en el DataGridView", ex);
}
}
/// <summary>
/// Registra una nueva utilería en la base de datos.
/// </summary>
private void btnRegisterProp_Click(object sender, EventArgs e)
{
string propName = txtPropName.Text.Trim();
if (!int.TryParse(numCantidad.Text, out int propQuantity))
{
ShowWarningMessage("Ingrese una cantidad válida (número entero).");
return;
}
string query = "INSERT INTO Utileria (Nombre, Cantidad) VALUES (@Nombre, @Cantidad)";
try
{
using (SqlConnection conn = new SqlConnection(sqlServerConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Nombre", propName);
cmd.Parameters.AddWithValue("@Cantidad", propQuantity);
conn.Open();
cmd.ExecuteNonQuery();
}
}
ShowInfoMessage("Utilería añadida correctamente.");
LoadDataToDataGridView();
}
catch (Exception ex)
{
ShowErrorMessage("Error al añadir la utilería", ex);
}
}
/// <summary>
/// Carga los datos de una fila seleccionada en los campos de texto.
/// </summary>
private void dgvUtileria_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = dgvUtileria.Rows[e.RowIndex];
txtPropName.Text = row.Cells["Nombre"].Value?.ToString() ?? string.Empty;
numCantidad.Text = row.Cells["Cantidad"].Value?.ToString() ?? string.Empty;
}
}
/// <summary>
/// Actualiza los datos de una utilería seleccionada.
/// </summary>
private void btnUpdateService_Click(object sender, EventArgs e)
{
if (dgvUtileria.SelectedRows.Count == 0)
{
ShowWarningMessage("Seleccione una utilería para actualizar.");
return;
}
DataGridViewRow row = dgvUtileria.SelectedRows[0];
int id = Convert.ToInt32(row.Cells["IdUtileria"].Value);
string propName = txtPropName.Text.Trim();
if (!int.TryParse(numCantidad.Text, out int propQuantity))
{
ShowWarningMessage("Ingrese una cantidad válida (número entero).");
return;
}
string query = "UPDATE Utileria SET Nombre = @Nombre, Cantidad = @Cantidad WHERE Id_utileria = @Id";
try
{
using (SqlConnection conn = new SqlConnection(sqlServerConnectionString))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.Parameters.AddWithValue("@Nombre", propName);
cmd.Parameters.AddWithValue("@Cantidad", propQuantity);
conn.Open();
cmd.ExecuteNonQuery();
}
}
ShowInfoMessage("Utilería actualizada correctamente.");
LoadDataToDataGridView();
}
catch (Exception ex)
{
ShowErrorMessage("Error al actualizar la utilería", ex);
}
}
#region Helper Methods
/// <summary>
/// Muestra un mensaje de error.
/// </summary>
private void ShowErrorMessage(string message, Exception ex)
{
MessageBox.Show($"{message}: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
/// <summary>
/// Muestra un mensaje de advertencia.
/// </summary>
private void ShowWarningMessage(string message)
{
MessageBox.Show(message, "Advertencia", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
/// <summary>
/// Muestra un mensaje informativo.
/// </summary>
private void ShowInfoMessage(string message)
{
MessageBox.Show(message, "Información", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
}
}