Datagridview: How to set a cell in editing mode?

212,163

Solution 1

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    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);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

Solution 2

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

Solution 3

I know this question is pretty old, but figured I'd share some demo code this question helped me with.

  • Create a Form with a Button and a DataGridView
  • Register a Click event for button1
  • Register a CellClick event for DataGridView1
  • Set DataGridView1's property EditMode to EditProgrammatically
  • Paste the following code into 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);
                }
            }
        }
    }
}

Note that the column index numbers can change from multiple button presses of button one, so I always refer to the columns by name not index value. I needed to incorporate David Hall's answer into my demo that already had ComboBoxes so his answer worked really well.

Share:
212,163
josecortesp
Author by

josecortesp

Estudiante de informática de la Universidad de Costa Rica. Junior Web Developer, Junior Windows Developer

Updated on April 17, 2021

Comments

  • josecortesp
    josecortesp about 3 years

    I need to programmatically set a cell in editing mode. I know that setting that cell as CurrentCell and then call the method BeginEdit(bool), it should happen, but in my case, it doesn't.

    I really want that, with my DGV with several columns, the user can ONLY select and also edit the first two. The other columns are already read-only, but the user can select them, and that is what I don't want.

    So I was thinking, tell the user to TAB everytime it has finished writing on the cell, then select the second cell, then tab again and it select and begin edit the next row's first cell...

    How can I do this?

  • josecortesp
    josecortesp over 14 years
    Thanks... First i was trying to use the SelectionChange event, and doing some hard (and uggly too) work to avoid stack overflow, since everytimes the selection changes it fires again. But now, i like the most your solution... And thanks +1 for the FAQ. I'm more used to web instead of winforms, but is good to know anyway. Thanks!
  • BoltBait
    BoltBait over 14 years
    This is exactly what I needed. Sort of... :) I was actually trying to update cell contents from outside of the grid that was tied to a datasource. I could put the new values on the screen, but the save button was saving the old values. I needed to put a CurrentCell before and EndEdit() after I updated the values. Your answer got me totally on the right track. Thanks!
  • IbrarMumtaz
    IbrarMumtaz over 11 years
    Avoided the need to ask a similar question - ty
  • HodlDwon
    HodlDwon over 11 years
    +1 saved me from asking a question as well, I posted a fully functional sample as a wiki to this question using this suggested method.
  • David Hall
    David Hall almost 11 years
    @StealthRabbi thanks - I've updated the link. It's a Microsoft download, so should be stable, but then, so was the original! If it breaks again, one can find by searching for DataGridView FAQ
  • deloreyk
    deloreyk over 10 years
    A document you can trust: "Windows Froms 2.0" -FAQ Document, 1st sentence.
  • David Hall
    David Hall over 10 years
    @KevinDeLorey ha, never noticed that! The typo aside, it is actually worth a look :)
  • Sverrir Sigmundarson
    Sverrir Sigmundarson over 5 years
    Thanks for the doc link, even in 2018 this doc is really useful (despite any spelling mistakes)