Form1.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. using System;
  2. using System.Data;
  3. using System.Windows.Forms;
  4. using Npgsql;
  5. namespace CarApp
  6. {
  7. public partial class Form1 : Form
  8. {
  9. private string connString = "Host=245e1-rw.db.pub.dbaas.postgrespro.ru;Database=dbimport;Username=nikolaeva_sa;Password=$SD$fF7U$z#;SSL Mode=Require;Trust Server Certificate=true;";
  10. public Form1()
  11. {
  12. InitializeComponent();
  13. }
  14. private bool IsValidInput(string input)
  15. {
  16. if (string.IsNullOrWhiteSpace(input))
  17. return false;
  18. string[] forbidden = { "--", ";", "DROP", "DELETE", "INSERT", "UPDATE", "ALTER" };
  19. foreach (string f in forbidden)
  20. {
  21. if (input.ToUpper().Contains(f))
  22. return false;
  23. }
  24. return true;
  25. }
  26. private void button1_Click(object sender, EventArgs e)
  27. {
  28. try
  29. {
  30. using (var cn = new NpgsqlConnection(connString))
  31. {
  32. cn.Open();
  33. string sql = "SELECT car_id, brand, model, year, price FROM car";
  34. var da = new NpgsqlDataAdapter(sql, cn);
  35. DataTable dt = new DataTable();
  36. da.Fill(dt);
  37. dataGridView1.DataSource = dt;
  38. }
  39. MessageBox.Show("Данные загружены!");
  40. }
  41. catch (Exception ex)
  42. {
  43. MessageBox.Show("Ошибка: " + ex.Message);
  44. }
  45. }
  46. private void button2_Click(object sender, EventArgs e)
  47. {
  48. if (!string.IsNullOrWhiteSpace(textBox1.Text) && !IsValidInput(textBox1.Text))
  49. {
  50. MessageBox.Show("Некорректный поисковый запрос!", "Ошибка");
  51. return;
  52. }
  53. try
  54. {
  55. using (var cn = new NpgsqlConnection(connString))
  56. {
  57. cn.Open();
  58. string sql = "SELECT car_id, brand, model, year, price FROM car WHERE brand ILIKE @s";
  59. var cmd = new NpgsqlCommand(sql, cn);
  60. cmd.Parameters.AddWithValue("@s", "%" + textBox1.Text + "%");
  61. var da = new NpgsqlDataAdapter(cmd);
  62. DataTable dt = new DataTable();
  63. da.Fill(dt);
  64. dataGridView1.DataSource = dt;
  65. }
  66. }
  67. catch (Exception ex)
  68. {
  69. MessageBox.Show("Ошибка: " + ex.Message);
  70. }
  71. }
  72. private void button3_Click(object sender, EventArgs e)
  73. {
  74. SaveFileDialog sfd = new SaveFileDialog();
  75. sfd.Filter = "CSV|*.csv";
  76. sfd.FileName = "cars.csv";
  77. if (sfd.ShowDialog() == DialogResult.OK)
  78. {
  79. using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName))
  80. {
  81. for (int i = 0; i < dataGridView1.Columns.Count; i++)
  82. sw.Write(dataGridView1.Columns[i].HeaderText + (i == dataGridView1.Columns.Count - 1 ? "" : ";"));
  83. sw.WriteLine();
  84. foreach (DataGridViewRow row in dataGridView1.Rows)
  85. {
  86. if (row.IsNewRow) continue;
  87. for (int i = 0; i < dataGridView1.Columns.Count; i++)
  88. sw.Write(row.Cells[i].Value?.ToString() + (i == dataGridView1.Columns.Count - 1 ? "" : ";"));
  89. sw.WriteLine();
  90. }
  91. }
  92. MessageBox.Show("Экспорт завершён!");
  93. }
  94. }
  95. private void button4_Click(object sender, EventArgs e)
  96. {
  97. // ДИАЛОГ ДОБАВЛЕНИЯ
  98. Form addForm = new Form();
  99. addForm.Text = "Добавить авто";
  100. addForm.Size = new System.Drawing.Size(320, 280);
  101. addForm.StartPosition = FormStartPosition.CenterParent;
  102. TextBox txtReg = new TextBox() { Location = new System.Drawing.Point(120, 20), Size = new System.Drawing.Size(150, 23) };
  103. TextBox txtBrand = new TextBox() { Location = new System.Drawing.Point(120, 55), Size = new System.Drawing.Size(150, 23) };
  104. TextBox txtModel = new TextBox() { Location = new System.Drawing.Point(120, 90), Size = new System.Drawing.Size(150, 23) };
  105. TextBox txtYear = new TextBox() { Location = new System.Drawing.Point(120, 125), Size = new System.Drawing.Size(150, 23) };
  106. TextBox txtPrice = new TextBox() { Location = new System.Drawing.Point(120, 160), Size = new System.Drawing.Size(150, 23) };
  107. addForm.Controls.Add(new Label() { Text = "Рег. номер:", Location = new System.Drawing.Point(20, 23), Size = new System.Drawing.Size(80, 23) });
  108. addForm.Controls.Add(txtReg);
  109. addForm.Controls.Add(new Label() { Text = "Марка:", Location = new System.Drawing.Point(20, 58), Size = new System.Drawing.Size(80, 23) });
  110. addForm.Controls.Add(txtBrand);
  111. addForm.Controls.Add(new Label() { Text = "Модель:", Location = new System.Drawing.Point(20, 93), Size = new System.Drawing.Size(80, 23) });
  112. addForm.Controls.Add(txtModel);
  113. addForm.Controls.Add(new Label() { Text = "Год:", Location = new System.Drawing.Point(20, 128), Size = new System.Drawing.Size(80, 23) });
  114. addForm.Controls.Add(txtYear);
  115. addForm.Controls.Add(new Label() { Text = "Цена:", Location = new System.Drawing.Point(20, 163), Size = new System.Drawing.Size(80, 23) });
  116. addForm.Controls.Add(txtPrice);
  117. Button btnOk = new Button() { Text = "OK", Location = new System.Drawing.Point(70, 200), Size = new System.Drawing.Size(70, 30), DialogResult = DialogResult.OK };
  118. Button btnCancel = new Button() { Text = "Отмена", Location = new System.Drawing.Point(160, 200), Size = new System.Drawing.Size(70, 30), DialogResult = DialogResult.Cancel };
  119. addForm.Controls.Add(btnOk);
  120. addForm.Controls.Add(btnCancel);
  121. if (addForm.ShowDialog() == DialogResult.OK)
  122. {
  123. if (!IsValidInput(txtBrand.Text))
  124. {
  125. MessageBox.Show("Некорректный ввод марки!", "Ошибка");
  126. return;
  127. }
  128. if (!IsValidInput(txtModel.Text))
  129. {
  130. MessageBox.Show("Некорректный ввод модели!", "Ошибка");
  131. return;
  132. }
  133. if (!IsValidInput(txtReg.Text))
  134. {
  135. MessageBox.Show("Некорректный ввод регистрационного номера!", "Ошибка");
  136. return;
  137. }
  138. int year;
  139. if (!int.TryParse(txtYear.Text, out year) || year < 1900 || year > DateTime.Now.Year + 1)
  140. {
  141. MessageBox.Show("Некорректный год!", "Ошибка");
  142. return;
  143. }
  144. decimal price;
  145. if (!decimal.TryParse(txtPrice.Text, out price) || price <= 0)
  146. {
  147. MessageBox.Show("Некорректная цена!", "Ошибка");
  148. return;
  149. }
  150. try
  151. {
  152. using (var cn = new NpgsqlConnection(connString))
  153. {
  154. cn.Open();
  155. string sql = "INSERT INTO car (reg_number, brand, model, year, price) VALUES (@r, @b, @m, @y, @p)";
  156. var cmd = new NpgsqlCommand(sql, cn);
  157. cmd.Parameters.AddWithValue("@r", txtReg.Text);
  158. cmd.Parameters.AddWithValue("@b", txtBrand.Text);
  159. cmd.Parameters.AddWithValue("@m", txtModel.Text);
  160. cmd.Parameters.AddWithValue("@y", year);
  161. cmd.Parameters.AddWithValue("@p", price);
  162. cmd.ExecuteNonQuery();
  163. }
  164. MessageBox.Show("Добавлено!");
  165. button1_Click(null, null);
  166. }
  167. catch (Exception ex)
  168. {
  169. MessageBox.Show("Ошибка: " + ex.Message);
  170. }
  171. }
  172. }
  173. // УДАЛИТЬ
  174. private void button5_Click(object sender, EventArgs e)
  175. {
  176. if (dataGridView1.SelectedRows.Count == 0)
  177. {
  178. MessageBox.Show("Выберите строку для удаления");
  179. return;
  180. }
  181. int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["car_id"].Value);
  182. string name = dataGridView1.SelectedRows[0].Cells["brand"].Value.ToString();
  183. DialogResult res = MessageBox.Show($"Удалить {name}?", "Подтверждение", MessageBoxButtons.YesNo);
  184. if (res == DialogResult.Yes)
  185. {
  186. try
  187. {
  188. using (var cn = new NpgsqlConnection(connString))
  189. {
  190. cn.Open();
  191. string sql = "DELETE FROM car WHERE car_id=@id";
  192. var cmd = new NpgsqlCommand(sql, cn);
  193. cmd.Parameters.AddWithValue("@id", id);
  194. cmd.ExecuteNonQuery();
  195. }
  196. MessageBox.Show("Удалено!");
  197. button1_Click(null, null);
  198. }
  199. catch (Exception ex)
  200. {
  201. MessageBox.Show("Ошибка: " + ex.Message);
  202. }
  203. }
  204. }
  205. }
  206. }