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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15424768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 16:47:03  来源:igfitidea点击:

datagridview cell edit and save functionality in windows forms?

c#winformsdatagridview

提问by adityaa

I'm working on datagridview in c# windows forms application and I'm loading the data from the database, now i want the user to be able to able to edit the cell value and save the value to the database, how to edit the cell value and how can i save the value to the database?

我正在 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"];

采纳答案by Fabio

One of the way to update a database with DataGridViewis using of DataGridView's events:

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

DataGridView.CellBeginEdit

DataGridView.CellValidating

DataGridView.CellEndEdit

Let say: private DataGridView dgv;Add handlers of events

比方说: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
}

回答by Jonathon Reinhart

Have a look at the DataGridViewEventslist. You need to subscribe to the appropriate event, and handle it accordingly. Namely, you're interested in DataGridView.CellValueChanged.

查看DataGridView事件列表。您需要订阅适当的事件,并相应地处理它。也就是说,您对DataGridView.CellValueChanged.

dataGridView1.CellValueChanged += ValueChangedHandler;

private void ValueChangedHandler(object sender, DataGridViewCellEventArgs e) {
    // do what is appropriate here.
}

回答by Sylca

Try to do this:

尝试这样做:

 private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
            {
                //after you've filled your ds, on event above try something like this
                try
                {

                    da.Update(ds);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

回答by Sylca

I used OleDb but you can use SQL. Here is the code I usually use for the same.

我使用了 OleDb,但您可以使用 SQL。这是我通常使用的代码。

OleDbCommand sCommand;
    OleDbDataAdapter sAdapter;
    OleDbCommandBuilder sBuilder;
    OleDbConnection connection;
    DataSet sDs;
    DataTable sTable;
    string myMode = "";
    private void BtnLoad_Click(object sender, EventArgs e)
    {
        string query = "SELECT * FROM [Table]";
        connection = new OleDbConnection(connectionString);
        connection.Open();
        sCommand = new OleDbCommand(query, connection);
        sAdapter = new OleDbDataAdapter(sCommand);
        sBuilder = new OleDbCommandBuilder(sAdapter);
        sDs = new DataSet();
        sAdapter.Fill(sDs, "Table");
        sTable = sDs.Tables["Table"];
        connection.Close();
        DataGrid.DataSource = sTable;
        DataGrid.ReadOnly = true;
        DataGrid.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
    }
    private void BtnAdd_Click(object sender, EventArgs e)
    {
        DataGrid.ReadOnly = false;
        myMode = "add";
    }
    private void BtnEdit_Click(object sender, EventArgs e)
    {
        DataGrid.ReadOnly = false;
        myMode = "edit";
    }
    private void BtnDelete_Click(object sender, EventArgs e)
    {
        myMode = "";
        if (MessageBox.Show("Do you want to delete this row ?", "Delete",      MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            DataGrid.Rows.RemoveAt(DataGrid.SelectedRows[0].Index);
            sAdapter.Update(sTable);
        }
    }
    private void BtnSave_Click(object sender, EventArgs e)
    {
        if (myMode == "add")
        {
            sAdapter.Update(sTable);
            MessageBox.Show("Prices Are Successfully Added.", "Saved.", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
        }
        else if (myMode == "edit")
        {
            string query = "UPDATE Table_Name SET " +
                "Column1 = '" + DataGrid.SelectedRows[0].Cells[0].Value.ToString() + "' ," +
                "Column2 = " + DataGrid.SelecteddRows[0].Cells[1].Value.ToString() + ", " +
                "WHERE CONDITION";
            connection = new OleDbConnection(connectionString);
            connection.Open();
            sCommand = new OleDbCommand(query, connection);
            sAdapter = new OleDbDataAdapter(sCommand);
            sBuilder = new OleDbCommandBuilder(sAdapter);
            sDs = new DataSet();
            sAdapter.Fill(sDs, "Table");
            sTable = sDs.Tables["Table"];
            connection.Close();
            DataGrid.DataSource = sTable;
            DataGrid.ReadOnly = true;
        }
    }

回答by Atul Sood

Add this line of code to enable editing on datagridview

添加这行代码以启用对 datagridview 的编辑

dtg.EditMode = DataGridViewEditMode.EditOnKeystroke;

Then use below event

然后使用下面的事件

private void dtg_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex > -1 && e.RowIndex > -1)
        {
            dtg.ReadOnly = false;
        }
}

The above two events will enable editing in datagridview.

以上两个事件将启用在 datagridview 中的编辑。

Then use below event to save the updated data back to db.

然后使用下面的事件将更新的数据保存回数据库。

private void dtg_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;
}