6

I have a question regarding DataGridView control in .NET.

I inserted a DataGridView from the toolbox and I connected it with a database that I setup in access. Then I added a column with buttons from the edit columns of the DataGridView tasks panel.

The click events of the DataGridView buttons work without a problem!

I want to perform a click on DataGridView button programmatically when I click another button outside of the DataGridView. How should I do this?

The code of the DataGridView is:

Private Sub dgvAnimSel_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) _
    Handles dgvAnimSel.CellContentClick
    Dim V As String = dgvAnimSel.Rows(e.RowIndex).Cells(0).Value
    If e.ColumnIndex = 3 Then
        If V = 1 Then
            If A1 = 1 Then
                'this is the uncheck state
                Me.dgvAnimSel.CurrentCell.Style.BackColor = Color.White
                Me.dgvAnimSel.CurrentCell.Style.ForeColor = Color.Black
                Me.dgvAnimSel.CurrentCell.Value = "Select"
                ItemTextNew = ItemTextOr + "1"
                ItemName = ListView1.FindItemWithText(ItemTextNew, False, 0, True)
                ListView1.Items.Remove(ItemName)
                A1 = 0
            Else
                'this is the check state
                Me.dgvAnimSel.CurrentCell.Style.BackColor = Color.Green
                Me.dgvAnimSel.CurrentCell.Style.ForeColor = Color.White
                Me.dgvAnimSel.CurrentCell.Value = "Selected"
                a = ListView1.Items.Add(" " + "Animation 1 ", 0)
                A1 = 1
            End If
        End If
End Sub

Thank you in advance!

2
  • 2
    I want to change the state of a DataGridView button programmatically Change to what state? What kind of change do you mean? Commented Jan 10, 2016 at 18:32
  • With the change state I mean to perform a click on the DataGridView button sorry my mistake! :) Commented Jan 10, 2016 at 18:39

3 Answers 3

6

You can use either of the following options:

  • Calling the event handler of CellContentClick like a normal method by creating an instance of DataGridViewCellEventArgs and pass it to the event handler method.
  • Or put the whole logic inside a method and call that method whenever you need, from CellContentClick of the DataGridView or Click of the button.

VB.NET

Example 1 - Perform Click for DataGridView Button Cell by calling the event handler

To programmatically click on button in specific row, you can call the method that you created as event handler of CellContentClick event, using suitable DataGridViewCellEventArgs as e and your DataGridView as sender:

Private Sub AnotherButton_Click(sender As Object, e As EventArgs) _
    Handles AnotherButton.Click
    ' zero based ColumnIndex of your button column= 3 (for example)
    ' zero based RowIndex that you want to click on its button column = 2 (for example)
    Dim arg = New DataGridViewCellEventArgs(3, 2) 
    DataGridView1_CellContentClick(DataGridView1, arg)
End Sub

Private Sub DataGridView1_CellContentClick(sender As Object, _
    e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    MessageBox.Show(e.RowIndex.ToString())
End Sub

Example 2 - Putting the logic in another method and call the method when you need

As another option you can put the logic related to click on a cell button in a method, dependent from Cell and Row objects and only pass suitable values to that method. Then you can call the method wherever you need.

Private Sub DoSomething(rowIndex as Integer, columnIndex as Integer)
    MessageBox.Show(rowIndex.ToString())
End Sub

Private Sub AnotherButton_Click(sender As Object, e As EventArgs) _
    Handles AnotherButton.Click
    ' zero based ColumnIndex of your button column= 3 (for example)
    ' zero based RowIndex that you want to click on its button column = 2 (for example)
    DoSomething(2, 3) 
End Sub

Private Sub DataGridView1_CellContentClick(sender As Object, _
    e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    DoSomething(e.RowIndex, e.ColumnIndex)
End Sub

C#

Example 1 - Perform Click for DataGridView Button Cell by calling the event handler

To programmatically click on button in specific row, you can call the method that you created as event handler of CellContentClick event, using suitable DataGridViewCellEventArgs as e and your DataGridView as sender:

private void anotherButton_Click(object sender, EventArgs e)
{
    ' zero based ColumnIndex of your button column= 3 (for example)
    ' zero based RowIndex that you want to click on its button column = 2 (for example)
    var arg = new DataGridViewCellEventArgs(3, 2); 
    dataGridView1_CellContentClick(dataGridView1, arg);
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    MessageBox.Show(e.RowIndex.ToString());
}

Example 2 - Putting the logic in another method and call the method when you need

As another option you can put the logic related to click on a cell button in a method, dependent from Cell and Row objects and only pass suitable values to that method. Then you can call the method wherever you need.

private void DoSomething(int rowIndex, int columnIndex)
{
    MessageBox.Show(rowIndex.ToString());
}

private void anotherButton_Click(object sender, EventArgs e)
{
    ' zero based ColumnIndex of your button column= 3 (for example)
    ' zero based RowIndex that you want to click on its button column = 2 (for example)
    DoSomething(2, 3); 
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    DoSomething(e.RowIndex, e.ColumnIndex);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help guys! Mr Ivan I tried what you suggested but it does not seam to work... Mr Reza, your approach works but when I run the app it displays a DataGridView Default Error Dialog with System.Exception: Selected is not a valid value for Int32... What does this mean? Again thank you very much!
To test my answer independent from your program,arrange a simple test as I did. MessageBox.Show(e.RowIndex.ToString()) that I forgot to use .ToString() Then If it worked (That will work properly) it means the solution is OK and you should apply it to your program.
@Kostas I didn't check Ivan's answer, but I think it should be useful. Also you should inform Ivan if you want to ask questions or if you need more help, by commenting below his answer.
1

If you want to generate programmatically click on DataGridViewButtonCell instance, you can use DataGridViewCell.AccessibilityObject property and call DoDefaultAction method.

Something like this (sorry for C#, I'm sure you can translate it to VB):

DataGridViewButtonCell otherCell = ...;
otherCell.AccessibilityObject.DoDefaultAction();

Test:

using System;
using System.Linq;
using System.Windows.Forms;

namespace Samples
{
    static class Program
    {
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var form = new Form();
            var grid = new DataGridView { Dock = DockStyle.Fill, Parent = form, AutoGenerateColumns = false };
            var col0 = new DataGridViewTextBoxColumn { Name = "Col0", HeaderText = "Col0", DataPropertyName = "Col0" };
            var col1 = new DataGridViewButtonColumn { Name = "Col1", HeaderText = "Col1", DataPropertyName = "Col1" };
            grid.Columns.AddRange(new DataGridViewColumn[] { col0, col1 });
            grid.CellContentClick += (sender, e) =>
            {
                MessageBox.Show("Clicked Cell[" + e.RowIndex + "," + e.ColumnIndex + "]");
            };
            grid.DataSource = Enumerable.Range(0, 10).Select(n => new { Col0 = "Cell[" + n + ",0]", Col1 = "Cell[" + n + ",1]" }).ToList();
            var button = new Button { Dock = DockStyle.Bottom, Parent = form, Text = "Click" };
            button.Click += (sender, e) =>
            {
                var cell = grid.CurrentRow.Cells[col1.Index];
                cell.AccessibilityObject.DoDefaultAction();
            };
            Application.Run(form);
        }
    }
}

1 Comment

@Kostas It also works fine. Don't forget to add a reference to Accessibility assembly.
0

you are encountering trouble because unlike the Button control which exposes the method:

public void PerformClick();

the DatagridView family do not expose this method. @Microsoft : I am not proud of you!

However the DataGridView class exposes the CurrentCell property:

public DataGridViewCell CurrentCell { get; set; }

and this property triggers the event CurrentCellChanged:

    public event EventHandler CurrentCellChanged;

Hence my suggestion is that instead of putting your handler on Click, put it on CurrentCellChanged and perform the triggering by setting the current cell instead of looking for a Click() method which does not exist inside the framework, like this:

DataGridViewCell currentCell = ...;
grid.CurrentCell = currentCell;

If you use this solution, I will be happy to know it by you voting with the button on the left.

Youtube channel: https://youtube.com/channel/UCVww4lxZnKGx_5I4clpb52w

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.