Datagridview:如何设置单元格为编辑模式?

39

我需要以编程方式设置一个单元格处于编辑模式。我知道将该单元格设置为当前单元格,然后调用BeginEdit(bool)方法,应该会发生这种情况,但在我的情况下,它并没有发生。

我真的希望,对于我的具有多个列的DGV,用户只能选择并编辑前两个列。其他列已经是只读的,但用户仍然可以选择它们,这就是我不想要的。

所以我在思考,告诉用户每次完成单元格写入后按TAB键,然后选择第二个单元格,然后再按一次tab键,它将选择并开始编辑下一行的第一个单元格...

我该怎么做?

7个回答

88
设置CurrentCell,然后调用BeginEdit(true)对我很有效。
以下代码展示了KeyDown事件的事件处理程序,用于设置单元格可编辑。
我的示例仅实现了所需按键覆盖中的一个,但理论上其他按键应该也可以使用相同的方法。(我总是将[0][0]单元格设置为可编辑,但是任何其他单元格都应该可以工作)
private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
    {
        e.Handled = true;
        DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
        dataGridView1.CurrentCell = cell;
        dataGridView1.BeginEdit(true);               
    }
}

如果你之前没有找到它,DataGridView FAQ 是一个很好的资源,由 DataGridView 控件的程序经理编写,涵盖了你可能想要使用该控件做的大部分事情。

1
首先,我尝试使用SelectionChange事件,并做了一些艰难(而且也很丑陋)的工作来避免堆栈溢出,因为每次选择更改时它都会再次触发。 但现在,我最喜欢你的解决方案... 谢谢+1的常见问题解答。虽然我更习惯于Web而不是WinForms,但无论如何都是好的了解。 谢谢! - josecortesp
1
这正是我所需要的。有点... :) 实际上,我正在尝试从与数据源绑定的网格外部更新单元格内容。我可以将新值放在屏幕上,但保存按钮却保存了旧值。我需要在更新值之前放置一个CurrentCell,然后在EndEdit()之后。你的答案让我完全走上了正确的轨道。谢谢! - BoltBait
@StealthRabbi 谢谢 - 我已经更新了链接。它是一个微软下载链接,所以应该很稳定,但原始链接也是如此!如果再次出现问题,可以通过搜索“DataGridView FAQ”来找到答案。 - David Hall
3
一份可信赖的文档:“Windows Forms 2.0” - FAQ文档,第一句话。 - deloreyk
2
@KevinDeLorey 哈,从来没有注意过这点!除了错别字外,它实际上值得一看 :) - David Hall
显示剩余3条评论

6
private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  if (DgvRoomInformation.CurrentCell.ColumnIndex == 4)  //example-'Column index=4'
  {
    DgvRoomInformation.BeginEdit(true);   
  }
}

5

嗯,我会检查您的列是否设置为ReadOnly。我从未使用过BeginEdit,但也许有一些合法的用途。一旦您执行了dataGridView1.Columns[".."].ReadOnly = False;,那些不是ReadOnly的字段就可以编辑了。您可以使用DataGridView CellEnter事件确定哪个单元格被输入,然后在您将编辑从前两列传递到下一组列并关闭最后两列的编辑之后,在这些单元格上打开编辑。


2

我知道这个问题相当古老,但我想分享一些演示代码,这个问题帮助了我。

  • 创建一个带有ButtonDataGridView的表单
  • 为button1注册Click事件
  • 为DataGridView1注册CellClick事件
  • 将DataGridView1的属性EditMode设置为EditProgrammatically
  • 将以下代码粘贴到Form1中:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        DataTable m_dataTable;
        DataTable table { get { return m_dataTable; } set { m_dataTable = value; } }

        private const string m_nameCol = "Name";
        private const string m_choiceCol = "Choice";

        public Form1()
        {
            InitializeComponent();
        }

        class Options
        {
            public int m_Index { get; set; }
            public string m_Text { get; set; }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            table = new DataTable();
            table.Columns.Add(m_nameCol);
            table.Rows.Add(new object[] { "Foo" });
            table.Rows.Add(new object[] { "Bob" });
            table.Rows.Add(new object[] { "Timn" });
            table.Rows.Add(new object[] { "Fred" });

            dataGridView1.DataSource = table;

            if (!dataGridView1.Columns.Contains(m_choiceCol))
            {
                DataGridViewTextBoxColumn txtCol = new DataGridViewTextBoxColumn();
                txtCol.Name = m_choiceCol;
                dataGridView1.Columns.Add(txtCol);
            }

            List<Options> oList = new List<Options>();
            oList.Add(new Options() { m_Index = 0, m_Text = "None" });
            for (int i = 1; i < 10; i++)
            {
                oList.Add(new Options() { m_Index = i, m_Text = "Op" + i });
            }

            for (int i = 0; i < dataGridView1.Rows.Count - 1; i += 2)
            {
                DataGridViewComboBoxCell c = new DataGridViewComboBoxCell();

                //Setup A
                c.DataSource = oList;
                c.Value = oList[0].m_Text;
                c.ValueMember = "m_Text";
                c.DisplayMember = "m_Text";
                c.ValueType = typeof(string);

                ////Setup B
                //c.DataSource = oList;
                //c.Value = 0;
                //c.ValueMember = "m_Index";
                //c.DisplayMember = "m_Text";
                //c.ValueType = typeof(int);

                //Result is the same A or B
                dataGridView1[m_choiceCol, i] = c;
            }
        }

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                if (dataGridView1.CurrentCell.ColumnIndex == dataGridView1.Columns.IndexOf(dataGridView1.Columns[m_choiceCol]))
                {
                    DataGridViewCell cell = dataGridView1[m_choiceCol, e.RowIndex];
                    dataGridView1.CurrentCell = cell;
                    dataGridView1.BeginEdit(true);
                }
            }
        }
    }
}

注意,按钮一的多次按压可能会导致列索引号发生变化,因此我总是按名称而不是索引值来引用列。我需要将David Hall的答案纳入我的演示中,而我的演示已经有了ComboBoxes,所以他的答案非常适合。

1
这个问题很旧了,但是提出的解决方案在我的情况下没有帮助。 在加载表单时选择单元格是必要的。 这个选项没有起作用:
private void FOperations_Load(object sender, EventArgs e)
{
  dgvOperations.CurrentCell = dgvOperations[nameof(Operation.DisplayName), 0];
  dgvOperations.Select();
}

如果在“布局”事件中进行单元格选择,则一切都会成功。
private void dgvOperation_Layout(object sender, LayoutEventArgs e)
{
  dgvOperations.CurrentCell = dgvOperations[nameof(Operation.DisplayName), 0];
  dgvOperations.Select();
}

0

我知道这是一个老问题,但是没有一个答案适用于我,因为我想要可靠地(始终能够)在可能执行其他事件(如工具栏按钮单击、菜单选择等)后将单元格设置为编辑模式,这些事件可能会影响这些事件返回后的默认焦点。最终我需要一个计时器和调用。以下代码位于从DataGridView派生的新组件中。这段代码允许我随时调用myXDataGridView.CurrentRow_SelectCellFocus(myDataPropertyName);来任意设置数据绑定单元格为编辑模式(假设该单元格不在只读模式下)。

// If the DGV does not have Focus prior to a toolbar button Click, 
// then the toolbar button will have focus after its Click event handler returns.
// To reliably set focus to the DGV, we need to time it to happen After event handler procedure returns.

private string m_SelectCellFocus_DataPropertyName = "";
private System.Timers.Timer timer_CellFocus = null;

public void CurrentRow_SelectCellFocus(string sDataPropertyName)
{
  // This procedure is called by a Toolbar Button's Click Event to select and set focus to a Cell in the DGV's Current Row.
  m_SelectCellFocus_DataPropertyName = sDataPropertyName;
  timer_CellFocus = new System.Timers.Timer(10);
  timer_CellFocus.Elapsed += TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Start();
}


void TimerElapsed_CurrentRowSelectCellFocus(object sender, System.Timers.ElapsedEventArgs e)
{
  timer_CellFocus.Stop();
  timer_CellFocus.Elapsed -= TimerElapsed_CurrentRowSelectCellFocus;
  timer_CellFocus.Dispose();
  // We have to Invoke the method to avoid raising a threading error
  this.Invoke((MethodInvoker)delegate
  {
    Select_Cell(m_SelectCellFocus_DataPropertyName);
  });
}


private void Select_Cell(string sDataPropertyName)
{
  /// When the Edit Mode is Enabled, set the initial cell to the Description
  foreach (DataGridViewCell dgvc in this.SelectedCells) 
  {
    // Clear previously selected cells
    dgvc.Selected = false; 
  }
  foreach (DataGridViewCell dgvc in this.CurrentRow.Cells)
  {
    // Select the Cell by its DataPropertyName
    if (dgvc.OwningColumn.DataPropertyName == sDataPropertyName)
    {
      this.CurrentCell = dgvc;
      dgvc.Selected = true;
      this.Focus();
      return;
    }
  }
}

0

我终于找到了答案。在我的情况下,我想要在添加新行后选择特定的索引或项,但这也适用于其他情况。

单元格本身并不包含组合框控件。DataGridView (DGV) 拥有当前单元格的控件。因此,您必须将当前单元格设置为组合框单元格,然后进入编辑模式,将 dgv 控件转换为 ComboBox,然后您就可以访问 selectedIndex 和 selectedItem 方法。

Dim rowIndex = myDgv.Rows.Add()
myDgv.ClearSelection()
myDgv.CurrentCell = myDgv.Rows(rowIndex).Cells("colName")
myDgv.BeginEdit(True)
Dim myCombo as ComboBox = CType(myDgv.EditingControl, ComboBox)
myCombo.SelectedIndex = 3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接