techmanc
techmanc

Reputation: 293

datagridView edits

I have a datagridview that is bound to a SQLite database. Now, I wish to modify some fields in the datagridview.

There are 4 TEXT columns - Timestamp, Message, Type , Hash. Now I find a row, I want to right click it.. And it should have to option - "include" .. So, when i click include in the context menu, the Type column of my DGV should change to "include" from whatever it previously was... (I don't want it be enabled to edit.. I just want it to change within the program) How do i get the index where I have clicked and access that particular cell to modify it??

Upvotes: 2

Views: 279

Answers (2)

ba__friend
ba__friend

Reputation: 5903

private void dataGridView_DoubleClick(object sender, EventArgs e)
{  
    var grid = (DataGridView)sender;
    var point = grid.PointToClient(Cursor.Position);
    var hit = grid.HitTest(p.X, p.Y);      
    MessageBox.Show(string.Format("{0} / {1}", hit.ColumnIndex, hit.RowIndex));
}

Code is not compile tested, but in theory this should do the job.


dataGridView.Rows[rowIndex].Cells[cellIndex].Value = "something";

Upvotes: 1

David Hall
David Hall

Reputation: 33143

This code does what you want:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        BindingList<User> users = new BindingList<User>();
        users.Add(new User(){Name = "Fred", Included = "False", Title="Mr"});
        users.Add(new User(){Name = "Sue", Included = "False", Title="Dr"});
        users.Add(new User(){Name = "Jack", Included = "False", Title="Mr"});

        dataGridView1.DataSource = users;
    }


    private void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Right)
        {
            DataGridView.HitTestInfo hit = dataGridView1.HitTest(e.X, e.Y);

            if (hit.rowIndex >= 0)
            {
                dataGridView1.ClearSelection();
                dataGridView1.Rows[hit.RowIndex].Selected = true;
                contextMenuStrip1.Show(this.dataGridView1, new Point(e.X, e.Y));
            }
        }
    }

    private void includeToolStripMenuItem_Click_1(object sender, EventArgs e)
    {
        // Included was the name of the column to change in my example code,
        // you could also use the index of the column if you know it.
        dataGridView1.SelectedRows[0].Cells["Included"].Value = "Included";
    }
}

public class User
{
    public string Name { get; set; }
    public string Title { get; set; }
    public string Included { get; set; }
}

I couldn't think of a better method of informing the context menu which row was selected than actually using the selected row property of the DataGridView - you could also store this in a class level field, but I don't think that is quite as tidy.

Upvotes: 1

Related Questions