在运行时动态设置DataGridViewColumn默认值 [英] Dynamically set DataGridViewColumn default value at runtime

查看:143
本文介绍了在运行时动态设置DataGridViewColumn默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DataGridView控件用于从数据库中的单个表中编辑/更新/删除记录。我已经覆盖了DataGridView控件来添加以下内容:

I have a DataGridView control that is using to edit/update/delete records from a single table in a database. I have overridden the DataGridView control to add the following:

    private int employeeID;

    public int DefaultEmployeeID
    {
        get { return employeeID; }
        set { employeeID = value; }
    }

    protected override void OnUserAddedRow(DataGridViewRowEventArgs e)
    {
        e.Row.Cells[0].Value = employeeID;
        base.OnUserAddedRow(e);
    }

当用户从数据库加载不同的员工时,DefaultEmployeeID属性设置为员工的身份证。我知道OnUserRowAdded事件正在正常启动,employeeID被设置为正确的值,我是正面的我有正确的单元格。但是,值仍然设置为0。

When the user loads a different employee from the database, the DefaultEmployeeID attribute is then set to the employee's ID. I know that the OnUserRowAdded event is firing properly, employeeID is being set to the correct value, and I'm positive I have the correct cell. However, the value is still being set to 0.

什么给了?感谢提前。

推荐答案

您的问题来自于 UserAddedRow 模板行的事件触发(最底端的一个,用于向网格添加新行) - 设置正确的值,但错误的行。

Your problem comes from the fact that UserAddedRow event fires for the template row (the one at the very bottom, used to add new rows to grid) - you set correct value, but for wrong row.

解决问题的简单方法:

protected override void OnUserAddedRow(DataGridViewRowEventArgs e)
{
    // get the index for "1 before last row" - the one which you in fact edit/add
    int actualRowIndex = this.Rows.Count - 2; 
    this.Rows[actualRowIndex].Cells[0].Value = employeeID;
    base.OnUserAddedRow(e);
}

我已经运行这个简单的例子来说明我在说什么。一旦用户开始输入模板行(左图),就会成为常规行,并插入新的模板行,这是事件args(右图)中的一个。

I've run this simple example to illustrate what rows I'm talking about. As soon as user starts typing in the template row (left image), it becomes regular row and new template row is inserted and that's the one in event args (right image).

这篇关于在运行时动态设置DataGridViewColumn默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆