繁体   English   中英

使用带有列href链接的数据表的datagridview

[英]datagridview using a datatable with a column href link

我试图弄清楚如何在我的c#winform项目中获取有界的datagridview列,使其像href链接一样显示。 问题是链接单击有效,但是任何普通用户都不会意识到他们可以单击该字段,因为该字段显示为字符串。 我需要该字段显示为蓝色,带有下划线,鼠标指针变成手...等。

当我在Datagrid中使用数据集时,我能够做到这一点。 我去了设计师,选择了“添加列”,并将其添加为“ DataGridViewLinkColumn”。我最近将项目更改为使用数据表,但我意识到这些字段不再显示为可单击的(如果我单击,它确实可以工作) )。

有什么理想的方法可以相对轻松地实现这一目标吗? 我进行了搜索,但我似乎找不到简单的解决方案,这让我感到有些惊讶。

将作为链接的单元格的类型更改为DataGridViewLinkCell ,然后处理对单元格的单击,如下所示:

void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow r in dataGridView1.Rows)
    {
        if (System.Uri.IsWellFormedUriString(r.Cells["Links"].Value.ToString(), UriKind.Absolute))
        {
            r.Cells["Links"] = new DataGridViewLinkCell();
            DataGridViewLinkCell c = r.Cells["Links"] as DataGridViewLinkCell;
        }
    }
}

// And handle the click too
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] is DataGridViewLinkCell)
    {
        System.Diagnostics.Process.Start( dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value as string);
    }
}

这可能会有所帮助:

        DataGridViewLinkColumn col1 = new DataGridViewLinkColumn();
        dataGridView1.Columns.Add(col1);
        dataGridView1.Columns[0].Name = "Links";

        DataGridViewRow dgvr = new DataGridViewRow();
        dgvr.CreateCells(dataGridView1);

        DataGridViewCell linkCell = new DataGridViewLinkCell();
        linkCell.Value = @"http:\\www.google.com";
        dgvr.Cells[0] = linkCell;

        dataGridView1.Rows.Add(dgvr);

它创建一个col,然后创建一个link类型的单元格。 您可以使用foreach循环来更有序地执行此操作,以处理更多项目。

祝好运!

看一下DataGridViewLinkColumn.LinkBehavior属性。 可以将其设置为AlwaysUnderline。

至于颜色,只需使用DataGridViewLinkColumn上的* LinkColor属性。

干杯

您可以在datagridview中为该列着色。 您可以在DataBindingComplete事件中执行以下操作:

private void dataGridView1_DataBindingComplete(object sender,
    DataGridViewBindingCompleteEventArgs e)
{
    if(this.mydatagridview.Columns["YourLinkColumnName"] != null)
    {    
        this.mydatagridview.Columns["YourLinkColumnName"].DefaultCellStyle.Font = ...
        this.mydatagridview.Columns["YourLinkColumnName"].DefaultCellStyle.ForeColor = ...
    }
}

您可以将字体设置为自己喜欢的字体(即带下划线,有颜色等)。

或者,如果您具有预制的列(不是自动生成的列),则可以在设计器中更改默认单元格样式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM