Hyperlink cell in Winforms DataGridView

You can change style of whole column in DataGridView. This is also a way to make column link column.

DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
        cellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        cellStyle.ForeColor = Color.LightBlue;
        cellStyle.SelectionForeColor = Color.Black;
        cellStyle.Font = new Font(FontFamily.GenericSansSerif, 10, FontStyle.Underline);
        dataGridView.Columns[1].DefaultCellStyle = cellStyle;

The DataGridView has a column type for this, the DataGridViewLinkColumn.

You need to databind this column type manually, where DataPropertyName sets the column to bind to in the grid's datasource:

DataGridViewLinkColumn col = new DataGridViewLinkColumn();
col.DataPropertyName = "Contact";
col.Name = "Contact";       
dataGridView1.Columns.Add(col);

You will also want to hide the autogenerated text column that comes from the Contact property of the grid.

Also, as with the DataGridViewButtonColumn you need to handle the user interaction yourself by responding to the CellContentClick event.


To then change cell values that are not hyperlinks to plain text you need to replace the link cell type with the textbox cell. In the example below I've done this during the DataBindingComplete event:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow r in dataGridView1.Rows)
    {
        if (!System.Uri.IsWellFormedUriString(r.Cells["Contact"].Value.ToString(), UriKind.Absolute))
        {
            r.Cells["Contact"] = new DataGridViewTextBoxCell();
        }
    }
}

You can also do this from the other direction, changing the DataGridViewTextBoxCell to a DataGridViewLinkCell I suggest this second since you will need to apply any changes that apply to all links to every cell.

This does have the advantage though that you will not then need to hide the autogenerated column, so may suit you best.

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow r in dataGridView1.Rows)
    {
        if (System.Uri.IsWellFormedUriString(r.Cells["Contact"].Value.ToString(), UriKind.Absolute))
        {
            r.Cells["Contact"] = new DataGridViewLinkCell();
            // Note that if I want a different link colour for example it must go here
            DataGridViewLinkCell c = r.Cells["Contact"] as DataGridViewLinkCell;
            c.LinkColor = Color.Green;
        }
    }
}