D. Thornhill D. Thornhill - 9 months ago 42
C# Question

C# Unable to pass tag with bound DataGridView control to another method

In my DataGridView I have a DataGridViewLinkCell and I would like to use Tags to pass an arbitrary string to the DGV's event handler.

This is my code for the LinkCell:

DataGridViewLinkCell searchWU = new DataGridViewLinkCell();
searchWU.Value = "Check";
searchWU.LinkVisited = false;
searchWU.Tag = "myTag";
this.hostMgmtDataGridView[colHostViewWUAvil, this.hostMgmtDataGridView.RowCount-2] = searchWU;

And then my code for the DGV's event handler:

public void hostMgmtDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
DataGridViewLinkCell derp = (DataGridViewLinkCell)sender;
debugLabel1.Text = derp.Tag.ToString();

The line
DataGridViewLinkCell derp = (DataGridViewLinkCell)sender;
produces the following error:

Unable to cast object of type 'System.Windows.Forms.DataGridView' to type 'System.Windows.Forms.DataGridViewLinkCell'.

If I change it to
DataGridView derp = (DataGridView)sender;
I get a Null Reference with
Object reference not set to an instance of an object.

I understand the errors, but I don't know how to tease out the LinkCell from it's associated DataGridView.

Any help would be appreciated - thanks!

Answer Source

object sender is the control, not the selected cell you can find the cell with DataGridViewCellEventArgs RowIndex and ColumnIndex properties

Try this (Untested)

    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        debugLabel1.Text = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Tag.ToString();