IT SHARE EDU
Hướng dẫn cách xóa dữ liệu từ c# bằng 2 cách khách nhau.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace kncsdlhocba
{
public partial class frmXoaDuLieu : Form
{
public frmXoaDuLieu()
{
InitializeComponent();
}
SqlConnection conec = null;
string Strcon = @”Server =DESKTOP-CR8PM8T\SQLEXPRESS; Database=CSDLSANPHAM ; User ID = sa; pwd =123″;
private void frmXoaDuLieu_Load(object sender, EventArgs e)
{
Hienthidulieulistbox();
}
private void Hienthidulieulistbox()
{
if (conec == null)
{
conec = new SqlConnection(Strcon);
}
if (conec.State == ConnectionState.Closed)
{
conec.Open();
}
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = “select * from SanPham”;
command.Connection = conec;
SqlDataReader reader = command.ExecuteReader();
lstSanPham.Items.Clear();
while (reader.Read())
{
int ma = reader.GetInt32(0);
string ten = reader.GetString(1);
lstSanPham.Items.Add(ma + ” – ” + ten);
}
reader.Close();
}
private void button1_Click(object sender, EventArgs e)
{
if (lstSanPham.SelectedIndex==-1)
{
MessageBox.Show(“Chưa chọn sản phẩm xóa”);
return;
}
string line = lstSanPham.SelectedItem.ToString();
string[] arr = line.Split(‘-‘);
int ma = int.Parse(arr[0]);
if (conec == null)
{
conec = new SqlConnection(Strcon);
}
if (conec.State == ConnectionState.Closed)
{
conec.Open();
}
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = “delete from SanPham where ma=”+ma;
command.Connection = conec;
int n = command.ExecuteNonQuery();
if (n>0)
{
Hienthidulieulistbox();
MessageBox.Show(“xóa Thàng Công”);
}
else
{
MessageBox.Show(“Xóa Thất Bại”);
}
}
// xóa dữ liệu có dùng paramater
private void btnXoaParamater_Click(object sender, EventArgs e)
{
if (lstSanPham.SelectedIndex == -1)
{
MessageBox.Show(“Chưa chọn sản phẩm xóa”);
return;
}
string line = lstSanPham.SelectedItem.ToString();
string[] arr = line.Split(‘-‘);
int ma = int.Parse(arr[0]);
if (conec == null)
{
conec = new SqlConnection(Strcon);
}
if (conec.State == ConnectionState.Closed)
{
conec.Open();
}
SqlCommand command = new SqlCommand();
command.CommandType = CommandType.Text;
command.CommandText = “delete from SanPham where ma=@ma”;
command.Connection = conec;
command.Parameters.Add(“@ma”, SqlDbType.Int).Value=ma;
int n = command.ExecuteNonQuery();
if (n>0)
{
Hienthidulieulistbox();
MessageBox.Show(“Xóa Thành Công”);
}
else
{
MessageBox.Show(“Xóa Thất Bại”);
}
}
}
}