winforms 如何从datagridview中检测所选行的更改?[关闭]

ztyzrc3y  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(40)

已关闭。此问题需要details or clarity。目前不接受回答。
**要改进此问题吗?**通过editing this post添加详细信息并阐明问题。

22天前关闭。
Improve this question
我需要“写”标签被删除时,用户选择一个项目。如果用户没有输入任何东西,它应该回去。


的数据
我决定捕捉更改事件,但没有任何效果。

int selected_row = 0;
private void dataGridView2_SelectionChanged(object sender, EventArgs e) {
    if (dataGridView2.CurrentRow.Index != selected_row) {
        selected_row = dataGridView2.CurrentRow.Index;
        MessageBox.Show("Changed.");
    }
}

字符串

s1ag04yj

s1ag04yj1#

你的观察是正确的:拦截SelectionChanged事件不会起作用,因为所有重要的事情都已经发生了。这里有一个简单的方法,我认为可能对你有用。要理解的是,当你编辑的时候,你并没有真正编辑单元格本身。你的标记将进入叠加在单元格顶部的DataGrid.EditingControl
因此,首先我建议通过清除dataGridView.EditingControlShowing事件的文本(从实际单元格复制到其中)来处理它。

dataGridView.EditingControlShowing += (sender, e) =>
{
    // Clear the editing control text.
    e.Control.Text = string.Empty;
};

字符串


的数据
然后处理dataGridView.CellValidating事件,检查e.FormattedValue属性,如果它是空的,或者如果你不喜欢你在那里看到的,取消编辑。这“应该”把文本放回编辑前的位置。

dataGridView.CellValidating += (sender, e) =>
{
    if(string.IsNullOrWhiteSpace(e.FormattedValue.ToString()))
    {
        dataGridView.CancelEdit();
    }
};



下面是我用来测试这个答案的代码:

namespace dgv_with_revert_non_commit
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            dataGridView.DataSource = DataSource;

            dataGridView.CellValidating += (sender, e) =>
            {
                if(string.IsNullOrWhiteSpace(e.FormattedValue.ToString()))
                {
                    dataGridView.CancelEdit();
                }
            };
            dataGridView.EditingControlShowing += (sender, e) =>
            {
                // Clear the editing control text.
                e.Control.Text = string.Empty;
            };

            for (int i = 0; i < 10; i++)
            {
                DataSource.Add(new Record { Index = i });
            }
        }
        readonly BindingList<Record> DataSource = new BindingList<Record>();
    }


此示例使用带有此Record类的绑定数据源。

class Record
    {
        public int Index { get; set; }
        public string BurstTime { get; set; } = "Write";
    }
}

相关问题