1

I'm trying to make one function that will do some instructions for 2 (mouse) events in a DataGridView. In order to not repeat the instructions in both of events.

Here is my code:

        private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell)
            { Process.Start(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string); }
        }

        private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell)
            { Process.Start(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string); }
        }

So far I've tried to do this:

        private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            ReLink(e);
        }

        private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            ReLink(e);
        }

        //no matter which event I will specify, it is clear that it will only work for one event
        private void ReLink(DataGridViewCellMouseEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0 && dgv.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell)
            { Process.Start(dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string); }
        }

So, is there a way to solve this?...

1
  • 7
    Simple solution: Pass RowIndex and ColumnIndex as two separate int parameters. Then only the caller cares about “e”, or the type it has. Feb 28, 2020 at 8:54

2 Answers 2

6

you can go ahead with this

    private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        ReLink(e.ColumnIndex ,e.RowIndex);
    }

    private void dgv_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        ReLink(e.ColumnIndex ,e.RowIndex);
    }

    //no matter which event I will specify, it is clear that it will only work for one event
    private void ReLink(int colIndex, int rowIndex)
    {
        if (colIndex >= 0 && rowIndex >= 0 && dgv.Rows[rowIndex].Cells[colIndex] is DataGridViewLinkCell)
        { Process.Start(dgv.Rows[rowIndex].Cells[colIndex].Value as string); }
    }
0
0

e.RowIndex and e.ColumnIndex can be passed to the ReLink function instead of the type of event args.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.