DataGridView清除并重新获得焦点

时间:2016-10-20 22:19:21

标签: c# winforms datagridview

我正在使用Visual Studio 2015在C#中编写一个简单的WinForms程序,并尝试使用File / New来清除数据网格(它正在做的事情)并重新获得进一步数据输入的重点(它并没有完全做到)。

我正在使用DataSource:

BindingList<Record> Data = new BindingList<Record>();
...
Data.AllowNew = true;
...
dataGridView1.DataSource = Data;
dataGridView1.AllowUserToAddRows = true;
dataGridView1.AllowUserToDeleteRows = true;

和File / New执行此操作:

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (Unsaved())
    {
        var r = MessageBox.Show("Proceed without saving?", "Unsaved data", MessageBoxButtons.YesNo);
        if (r != DialogResult.Yes)
            return;
    }
    Data.Clear();
    dataGridView1.Refresh();
    dataGridView1.Focus();
}

将网格重置为单个空行,但不会重新获得焦点。我错过了什么?

选择也应该有效,但不是。据我所知,WinForms项目不能简化为单个文件测试用例,但https://github.com/russellw/adder/blob/master/Form1.cs的实际代码非常接近最小的WinForms项目;重现的步骤只是在调试器下运行项目并选择File / New或ctrl-N快捷方式,观察焦点不会在网格视图上结束。

3 个答案:

答案 0 :(得分:2)

dataGridView的{​​{1}}和Select()方法不是您想要的。即使控制得到了重点,您也需要告诉控制什么是选定的单元格以进一步输入数据。 Focus()属性可以是解决方案。

你可以试试这个,

FirstDisplayedCell

结果选择蓝色),

enter image description here

如果你添加它(你可以在其他地方再次设置为默认值),

dataGridView1.CurrentCell = dataGridView1.FirstDisplayedCell;
dataGridView1.CurrentCell.Selected = true;

结果将是已选中,但未选中蓝色突出显示),

enter image description here

结果为gif,

enter image description here

希望有所帮助,

答案 1 :(得分:1)

从这里得到一些帮助:DataGridView - Focus a specific cell

希望这就是你要找的东西。

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
  if (Unsaved())
  {
    DialogResult r = MessageBox.Show("Proceed without saving?", "Unsaved data", MessageBoxButtons.YesNo);
    if (r != DialogResult.Yes)
     return;
  }
  Data.Clear();
  dataGridView1.Rows.Clear();
  //dataGridView1.Refresh();
  //dataGridView1.Focus();
  dataGridView1.CurrentCell = dataGridView1.Rows[0].Cells[0];
  dataGridView1.Rows[0].Cells[0].Selected = true;
  dataGridView1.BeginEdit(true);
}

答案 2 :(得分:0)

您可以尝试

dataGridView1.Select();

ActiveControl = dataGridView1;
相关问题