C# Winforms DataGridView中的超链接单元格

C# Winforms DataGridView中的超链接单元格,c#,datagridview,hyperlink,C#,Datagridview,Hyperlink,我有一个包含以下数据的datagridview ContactType | Contact ------------------------------------ Phone | 894356458 Email | xyz@abc.com 在这里,我需要显示数据“xyz@abc.com作为超链接,带有工具提示“单击以发送电子邮件”。数字数据“894356458”不应具有超链接 有什么想法吗 蒂

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

ContactType        |        Contact
------------------------------------
Phone              |       894356458
Email              |     xyz@abc.com
在这里,我需要显示数据“xyz@abc.com作为超链接,带有工具提示“单击以发送电子邮件”。数字数据“894356458”不应具有超链接

有什么想法吗


蒂亚

DataGridView的
有一个列类型,即

您需要手动数据绑定此列类型,其中
DataPropertyName
在网格的数据源中设置要绑定到的列:

DataGridViewLinkColumn col = new DataGridViewLinkColumn();
col.DataPropertyName = "Contact";
col.Name = "Contact";       
dataGridView1.Columns.Add(col);
您还需要隐藏来自网格的Contact属性的自动生成的文本列

此外,与
DataGridViewButtonColumn
一样,您需要通过响应
CellContentClick
事件来处理用户交互


要将非超链接的单元格值更改为纯文本,需要将链接单元格类型替换为文本框单元格。在下面的示例中,我在
databindingplete
事件期间完成了此操作:

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;

另一方面,datagridview的一个优点是,当响应手机内容点击时,你可以做一些事情,比如在点击电话号码时打开Voip服务。或者,你不能做相反的事情吗?默认情况下定义网格(TextBoxCell),然后在每行中超链接所需的单元格?只是想知道为什么默认设置为LinkCells,然后显式更改回LinkCellsTextBox@Brett超级链接栏有一些额外的属性和行为非常方便,比如访问的链接颜色和TrackVisitedState-当然你可以用另一种方法,但是我认为这种方法更方便。这个解决方案听起来不错。但是这个gridview的数据源是一个列表,其中myClass有属性——ContactType,Contact。所以它只是将数据源设置为gridview。我不会在这里手动添加行和列。在这种情况下,我们如何解决这个问题?David可能对此有更好的见解,但如果您的数据库/数据源结构是静态的,那么您仍然可以在DataGrid中手动定义列并进行绑定,而不会覆盖您定义的行为,我相信。我已经编辑了我的答案,解释如何在您的案例中更好地使用我的第一个选项(通过隐藏一列并使用DataPropertyName),以及在保留文本列的答案上提供第二个变体。