实现DataGridView删除指定行数据的操作方法
在工作中,经常需要对数据进行维护和管理,其中包括删除特定行数据。本文将介绍如何使用C Winform中的DataGridView控件实现删除指定行数据的功能。
添加DataGridView控件和主窗体刷新函数
首先,在Winform窗体上添加一个DataGridView控件,并设置合适的大小。为了在删除数据后立即刷新窗体内容,我们需要添加一个主窗体刷新函数。
```c
private void product_raiseCallBackRefreshEvent()
{
Product_Load(null, null); // 刷新窗体
}
```
创建查询条件存储过程
为了从数据库表中查询数据,我们需要创建一个查询条件存储过程。以下是一个示例:
```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显示数据代码
接下来,我们需要编写代码将查询到的数据显示在DataGridView中,并添加一个“选择”栏位。
```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 "料号";
[2].HeaderText "品名";
[3].HeaderText "规格";
[4].HeaderText "料号";
[5].HeaderText "密度";
[0].Width 50;
}
```
编写DataGridView控件点击事件
当用户点击DataGridView时,我们可以实现“选择”功能,选中特定行的数据。
```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)
{
();
}
}
```
实现删除按钮功能
最后,我们添加删除按钮的代码,确保用户可以点击按钮删除选中的行数据。
```c
private void toolStripButton3_Click(object sender, EventArgs e)
{
if (_ )
{
_();
}
if (_no "" _name "")
{
("请选择数据!", "提示", MessageBoxButtons.OK, );
return;
}
DialogResult dr ("确定要删除此产品信息吗?", "提示", 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();
}
```
通过以上步骤,我们成功实现了在C Winform中使用DataGridView删除指定行数据的操作。希望本文能够帮助您更好地管理和维护数据!
版权声明:本文内容由互联网用户自发贡献,本站不承担相关法律责任.如有侵权/违法内容,本站将立刻删除。