Hyperlink cell in Winforms DataGridView
c#, datagridview, hyperlink
Solution
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;
}
}
}
Problem
I have a datagridview with the following data. ``` ContactType | Contact ------------------------------------ Phone | 894356458 Email | xyz@abc.com ``` Here, I need to display the data "xyz@abc.com" as a hyperlink, with a tooltip "Click to send email". The number data "894356458" should not have a hyperlink. Any ideas??? TIA!