Winforms DataGridView 中的超链接单元格

2024-03-26

我有一个包含以下数据的 datagridview。

ContactType        |        Contact
------------------------------------
Phone              |       894356458
Email              |     [email protected] /cdn-cgi/l/email-protection

在这里,我需要显示数据“[电子邮件受保护] /cdn-cgi/l/email-protection”作为超链接,并带有工具提示“单击发送电子邮件”。号码数据“894356458”不应包含超链接。

有任何想法吗???

TIA!


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;
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Winforms DataGridView 中的超链接单元格 的相关文章

随机推荐