實(shí)現(xiàn)DataGridView刪除指定行數(shù)據(jù)的操作方法
在工作中,經(jīng)常需要對(duì)數(shù)據(jù)進(jìn)行維護(hù)和管理,其中包括刪除特定行數(shù)據(jù)。本文將介紹如何使用C Winform中的DataGridView控件實(shí)現(xiàn)刪除指定行數(shù)據(jù)的功能。 添加DataGridView控件和主窗體
在工作中,經(jīng)常需要對(duì)數(shù)據(jù)進(jìn)行維護(hù)和管理,其中包括刪除特定行數(shù)據(jù)。本文將介紹如何使用C Winform中的DataGridView控件實(shí)現(xiàn)刪除指定行數(shù)據(jù)的功能。
添加DataGridView控件和主窗體刷新函數(shù)
首先,在Winform窗體上添加一個(gè)DataGridView控件,并設(shè)置合適的大小。為了在刪除數(shù)據(jù)后立即刷新窗體內(nèi)容,我們需要添加一個(gè)主窗體刷新函數(shù)。
```c
private void product_raiseCallBackRefreshEvent()
{
Product_Load(null, null); // 刷新窗體
}
```
創(chuàng)建查詢條件存儲(chǔ)過程
為了從數(shù)據(jù)庫(kù)表中查詢數(shù)據(jù),我們需要?jiǎng)?chuàng)建一個(gè)查詢條件存儲(chǔ)過程。以下是一個(gè)示例:
```sql
USE [BF]
GO
CREATE PROCEDURE [dbo].[select_product]
AS
BEGIN
SELECT P_no, P_name, P_spc, P_type, P_pos FROM tproduct
END
```
編寫Winform中DataGridView顯示數(shù)據(jù)代碼
接下來,我們需要編寫代碼將查詢到的數(shù)據(jù)顯示在DataGridView中,并添加一個(gè)“選擇”欄位。
```c
private void show_data(DataGridView DG)
{
SqlCommand cmd new SqlCommand("select_product", _);
;
SqlDataAdapter dpt new SqlDataAdapter(cmd);
DataTable dt new DataTable();
(dt);
DataGridViewCheckBoxColumn ck new DataGridViewCheckBoxColumn();
(ck);
dt;
[0].HeaderText "選擇";
[1].HeaderText "料號(hào)";
[2].HeaderText "品名";
[3].HeaderText "規(guī)格";
[4].HeaderText "料號(hào)";
[5].HeaderText "密度";
[0].Width 50;
}
```
編寫DataGridView控件點(diǎn)擊事件
當(dāng)用戶點(diǎn)擊DataGridView時(shí),我們可以實(shí)現(xiàn)“選擇”功能,選中特定行的數(shù)據(jù)。
```c
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
if ( 0 > 0)
{
foreach (DataGridViewRow row in )
{
row.Cells[].Value false;
}
[].Cells[].Value true;
if ((bool)[].Cells[0].EditedFormattedValue)
{
products.p_no [].Cells[1]();
products.p_name [].Cells[2]();
}
else
{
products.p_no "";
products.p_name "";
}
}
}
catch (Exception ex)
{
();
}
}
```
實(shí)現(xiàn)刪除按鈕功能
最后,我們添加刪除按鈕的代碼,確保用戶可以點(diǎn)擊按鈕刪除選中的行數(shù)據(jù)。
```c
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (_ )
{
_();
}
if (_no "" _name "")
{
("請(qǐng)選擇數(shù)據(jù)!", "提示", MessageBoxButtons.OK, );
return;
}
DialogResult dr ("確定要?jiǎng)h除此產(chǎn)品信息嗎?", "提示", MessageBoxButtons.OKCancel, );
if (dr DialogResult.OK)
{
del_prd(_no, "delete from tdepartment");
product_raiseCallBackRefreshEvent();
}
_();
}
private void del_prd(string p_no, string sqlstr)
{
SqlCommand cmd new SqlCommand("", sqlstr " where p_no'39;" p_no "39;", _);
cmd.ExecuteNonQuery();
}
```
通過以上步驟,我們成功實(shí)現(xiàn)了在C Winform中使用DataGridView刪除指定行數(shù)據(jù)的操作。希望本文能夠幫助您更好地管理和維護(hù)數(shù)據(jù)!