I have a datagridview with the following data.
ContactType | Contact
------------------------------------
Phone | 894356458
Email | [email protected]
Here, I need to display the data "[email protected]" as a hyperlink, with a tooltip "Click to send email". The number data "894356458" should not have a hyperlink.
Any ideas???
TIA!
Adding ViewLink to DataGridView in VB.NET We can add hyperlink in the column of a DataGridView , the column type contains cells of type DataGridViewLinkCell and renders the text in the cell to look like a hyperlink. Link columns are not generated automatically when data binding a DataGridView control.
private void createGridView(DataTable gridviewdt) { MainGridView. Columns. Clear(); //Iterate through the columns of the datatable to set the data bound field dynamically. foreach (DataColumn col in gridviewdt.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With