The DataGridView
为此有一个列类型,DataGridViewLinkColumn http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewlinkcolumn.aspx.
您需要手动对此列类型进行数据绑定,其中DataPropertyName
设置要绑定到网格数据源中的列:
DataGridViewLinkColumn col = new DataGridViewLinkColumn();
col.DataPropertyName = "Contact";
col.Name = "Contact";
dataGridView1.Columns.Add(col);
您还需要隐藏来自网格的“联系人”属性的自动生成的文本列。
另外,与DataGridViewButtonColumn
您需要通过响应来自己处理用户交互CellContentClick
event.
然后,要将不是超链接的单元格值更改为纯文本,您需要将链接单元格类型替换为文本框单元格。在下面的示例中,我在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();
}
}
}
您也可以从另一个方向执行此操作,更改DataGridViewTextBoxCell
to a DataGridViewLinkCell
我建议这一秒,因为您需要应用适用于每个单元格的所有链接的任何更改。
这样做的好处是,您不需要隐藏自动生成的列,因此可能最适合您。
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;
}
}
}