我有一个datagridview与以下数据。
ContactType | Contact
------------------------------------
Phone | 894356458
Email | [email protected]
在这里,我需要将数据“[email protected]”显示为超链接,并提供工具提示“点击发送电子邮件”。数字数据“894356458”不应该有超链接。
有任何想法吗???
TIA!
DataGridView
有一个列类型,DataGridViewLinkColumn
。
您需要手动对此列类型进行数据绑定,其中DataPropertyName
将要绑定的列设置在网格的数据源中:
DataGridViewLinkColumn col = new DataGridViewLinkColumn();
col.DataPropertyName = "Contact";
col.Name = "Contact";
dataGridView1.Columns.Add(col);
您还需要隐藏来自网格的Contact属性的自动生成的文本列。
此外,与DataGridViewButtonColumn
一样,您需要通过响应CellContentClick
事件来处理用户交互。
若要更改不是纯文本超链接的单元格值,您需要将链接单元格类型替换为文本框单元格。在下面的例子中,我在DataBindingComplete
事件期间完成了这个:
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
更改为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;
}
}
}
您可以在DataGridView中更改整列的样式。这也是一种制作列链接列的方法。
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;