Загрузка данных
using System;
using System.Data;
using System.Windows.Forms;
using Microsoft.Data.SqlClient;
namespace WinFormsApp1
{
public partial class Form1 : Form
{
private readonly string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MainBD;Integrated Security=True;Encrypt=False;TrustServerCertificate=False";
private SqlDataAdapter adapter;
private DataTable dataTable;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
LoadData();
}
private void LoadData()
{
string query = "SELECT ID, FullName AS [ФИО], Position AS [Должность], Rate AS [Ставка], BaseSalary AS [Оклад], TaxRatePct AS [НДФЛ %], TaxAmount AS [НДФЛ руб], NetSalary AS [ЗП на руки], FOT AS [ФОТ] FROM StaffSalary";
try
{
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
adapter = new SqlDataAdapter(command);
SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
dataTable = new DataTable();
adapter.Fill(dataTable);
dataGridView1.DataSource = dataTable;
if (dataGridView1.Columns["ID"] != null)
dataGridView1.Columns["ID"].Visible = false;
string[] readOnlyColumns = { "НДФЛ %", "НДФЛ руб", "ЗП на руки", "ФОТ" };
foreach (string col in readOnlyColumns)
{
if (dataGridView1.Columns[col] != null)
dataGridView1.Columns[col].ReadOnly = true;
}
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка загрузки: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.AllowUserToAddRows = true;
MessageBox.Show("Введите данные в пустую строку внизу таблицы и нажмите 'Изменить' (Сохранить).", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void button3_Click(object sender, EventArgs e)
{
try
{
adapter.Update(dataTable);
MessageBox.Show("Изменения успешно сохранены!", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
LoadData();
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при сохранении: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.RowIndex < dataGridView1.Rows.Count - 1)
{
var result = MessageBox.Show("Вы уверены, что хотите удалить этого сотрудника?", "Подтверждение удаления", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
try
{
int id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["ID"].Value);
using (SqlConnection connection = new SqlConnection(connectionString))
{
string deleteQuery = "DELETE FROM StaffSalary WHERE ID = @ID";
using (SqlCommand command = new SqlCommand(deleteQuery, connection))
{
command.Parameters.AddWithValue("@ID", id);
connection.Open();
command.ExecuteNonQuery();
}
}
dataGridView1.Rows.RemoveAt(e.RowIndex);
MessageBox.Show("Сотрудник удален.", "Успех", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка при удалении: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}
USE MainBD;
GO
CREATE TABLE StaffSalary (
ID INT IDENTITY(1,1) PRIMARY KEY,
FullName NVARCHAR(150) NOT NULL,
Position NVARCHAR(100) NOT NULL,
Rate DECIMAL(3, 2) NOT NULL,
BaseSalary DECIMAL(10, 2) NOT NULL,
ActualSalary AS (BaseSalary * Rate),
TaxRatePct INT DEFAULT 13,
TaxAmount AS (ROUND((BaseSalary * Rate) * 0.13, 0)),
NetSalary AS ((BaseSalary * Rate) - ROUND((BaseSalary * Rate) * 0.13, 0)),
FOT AS ((BaseSalary * Rate) * 1.30)
);
INSERT INTO StaffSalary (FullName, Position, Rate, BaseSalary)
VALUES
(N'Иванов Иван Иванович', N'Директор', 1.0, 150000.00),
(N'Петрова Анна Сергеевна', N'Главный бухгалтер', 1.0, 100000.00),
(N'Сидоров Петр Петрович', N'Старший разработчик', 1.5, 120000.00),
(N'Кузнецова Елена Николаевна', N'Тестировщик', 0.5, 80000.00),
(N'Смирнов Алексей Владимирович', N'Системный администратор', 1.0, 70000.00);
SELECT
FullName AS [ФИО],
Position AS [Должность],
Rate AS [Ставка],
BaseSalary AS [Оклад],
TaxRatePct AS [НДФЛ в %],
TaxAmount AS [НДФЛ руб],
NetSalary AS [ЗП на руки],
FOT AS [ФОТ]
FROM StaffSalary;
namespace WinFormsApp1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
tableLayoutPanel1 = new TableLayoutPanel();
panel1 = new Panel();
button3 = new Button();
button2 = new Button();
button1 = new Button();
dataGridView1 = new DataGridView();
tableLayoutPanel1.SuspendLayout();
panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// tableLayoutPanel1
//
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100F));
tableLayoutPanel1.Controls.Add(panel1, 0, 2);
tableLayoutPanel1.Controls.Add(dataGridView1, 0, 1);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(0, 0);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 3;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 8.857809F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 91.14219F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 73F));
tableLayoutPanel1.Size = new Size(800, 450);
tableLayoutPanel1.TabIndex = 0;
//
// panel1
//
panel1.Controls.Add(button3);
panel1.Controls.Add(button2);
panel1.Controls.Add(button1);
panel1.Dock = DockStyle.Fill;
panel1.Location = new Point(3, 379);
panel1.Name = "panel1";
panel1.Size = new Size(794, 68);
panel1.TabIndex = 0;
//
// button3
//
button3.Location = new Point(233, 3);
button3.Name = "button3";
button3.Size = new Size(109, 56);
button3.TabIndex = 2;
button3.Text = "Удалить";
button3.TextAlign = ContentAlignment.BottomRight;
button3.UseVisualStyleBackColor = true;
button3.Click += button3_Click;
//
// button2
//
button2.Location = new Point(118, 3);
button2.Name = "button2";
button2.Size = new Size(109, 56);
button2.TabIndex = 1;
button2.Text = "Изменить";
button2.TextAlign = ContentAlignment.BottomRight;
button2.UseVisualStyleBackColor = true;
button2.Click += button2_Click;
//
// button1
//
button1.Location = new Point(3, 3);
button1.Name = "button1";
button1.Size = new Size(109, 56);
button1.TabIndex = 0;
button1.Text = "Добавить";
button1.TextAlign = ContentAlignment.BottomRight;
button1.UseVisualStyleBackColor = true;
button1.Click += button1_Click;
//
// dataGridView1
//
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.Location = new Point(3, 36);
dataGridView1.Name = "dataGridView1";
dataGridView1.Size = new Size(794, 337);
dataGridView1.TabIndex = 1;
dataGridView1.CellContentClick += dataGridView1_CellContentClick;
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(tableLayoutPanel1);
Name = "Form1";
Text = "Form1";
Load += Form1_Load;
tableLayoutPanel1.ResumeLayout(false);
panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
}
#endregion
private TableLayoutPanel tableLayoutPanel1;
private Panel panel1;
private Button button3;
private Button button2;
private Button button1;
private DataGridView dataGridView1;
}
}