using Npgsql;
using System.Data;
using System.Windows.Forms;
namespace post
{
public partial class Form1 : Form
{
private string connString = "Host=localhost;Port=5432;Username=postgres;Password=123456;Database=department";
public Form1()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
using (var cmd = new NpgsqlCommand("SELECT * FROM product", conn))
{
var dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridView1.DataSource = dt;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
using (var cmd = new NpgsqlCommand("INSERT INTO product (name, price) VALUES (@name, @price)", conn))
{
cmd.Parameters.AddWithValue("name", txtName.Text);
cmd.Parameters.AddWithValue("price", double.Parse(txtAddress.Text));
cmd.ExecuteNonQuery();
LoadData();
}
}
}
private void button2_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["id"].Value);
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
using (var cmd = new NpgsqlCommand("UPDATE product SET name=@name, price=@price WHERE id=@id", conn))
{
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters.AddWithValue("name", txtName.Text);
cmd.Parameters.AddWithValue("price", double.Parse(txtAddress.Text));
cmd.ExecuteNonQuery();
LoadData();
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
if (dataGridView1.SelectedRows.Count > 0)
{
int id = Convert.ToInt32(dataGridView1.SelectedRows[0].Cells["id"].Value);
using (var conn = new NpgsqlConnection(connString))
{
conn.Open();
using (var cmd = new NpgsqlCommand("DELETE FROM product WHERE id=@id", conn))
{
cmd.Parameters.AddWithValue("@id", id);
int rowsAffected = cmd.ExecuteNonQuery();
if (rowsAffected > 0)
{
MessageBox.Show("Successfully deleted data");
}
else
{
MessageBox.Show("No data was deleted. Check if the ID exists.");
}
LoadData();
}
}
}
}
}
}
Please use your own database, table and column name