gpt4 book ai didi

c# - datagridview 单元格编辑和保存 Windows 窗体中的功能?

转载 作者:太空狗 更新时间:2023-10-30 00:32:47 33 4
gpt4 key购买 nike

我正在使用 C# Windows 窗体应用程序中的 datagridview,我正在从数据库中加载数据,现在我希望用户能够编辑单元格值并将值保存到数据库中,如何编辑单元格值以及如何将值保存到数据库?

  SqlConnection con = new SqlConnection("user id=sa;password=123;database=employee");
SqlDataAdapter da = new SqlDataAdapter("select * from UserReg", con);
DataSet ds = new DataSet();
da.Fill(ds, "p");
dataGridView1.DataSource = ds.Tables["p"];

最佳答案

使用 DataGridView 更新数据库的方法之一是使用 DataGridView 的事件:

DataGridView.CellBeginEdit

DataGridView.CellValidating

DataGridView.CellEndEdit

假设:private DataGridView dgv;添加事件处理程序

dgv.CellBeginEdit += dgv_CellBeginEdit;
dgv.CellValidating += dgv_CellValidating;
dgv.CellEndEdit += dgv_CellEndEdit;

private void dgv_CellBeginEdit(Object sender, DataGridViewCellCancelEventArgs e)
{
//Here we save a current value of cell to some variable, that later we can compare with a new value
//For example using of dgv.Tag property
if(e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
this.dgv.Tag = this.dgv.CurrentCell.Value;
//Or cast sender to DataGridView variable-> than this handler can be used in another datagridview
}
}

private void dgv_CellValidating(Object sender, DataGridViewCellValidatingEventArgs e)
{
//Here you can add all kind of checks for new value
//For exapmle simple compare with old value and check for be more than 0
if(this.dgv.Tag = this.dgv.CurrentCell.Value)
e.Cancel = true; //Cancel changes of current cell
//For example used Integer check
int32 iTemp;
if (Int32.TryParse(this.dgv.CurrentCell.Value, iTemp) = True && iTemp > 0)
{
//value is ok
}
else
{
e.Cancel = True;
}
}

Private Sub dgvtest1_CellEndEdit(Object sender, DataGridViewCellEventArgs e)
{
//Because CellEndEdit event occurs after CellValidating event(if not cancelled)
//Here you can update new value to database
}

关于c# - datagridview 单元格编辑和保存 Windows 窗体中的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15424768/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com