将链接标签添加到绑定到DataSet的DataGridView单元格或列

时间:2012-11-02 06:45:59

标签: c# .net winforms datagridview

在我的项目中,我正在填充dataGridView dataSet(将DataGridView绑定到DataSet)。 dataGridView中的第一列必须是LinkLabels,我想在下面的代码中找到它。

dgvMain.DataSorce = ds.Tables[0];

我试过了:(不工作

DataGridViewLinkCell lnkCell = new DataGridViewLinkCell();
foreach (DataGridViewRow row in dgvMain.Rows)
{
    row.Cells[0] = lnkCell; // (ERROR) Cell provided already belongs to a grid. This operation is not valid.
}

也尝试了

for (int intCount = 0; intCount < dgvMain.Rows.Count; intCount++)
{
    dgvMain.Rows[intCount].Cells[0] = lnkCell; // (ERROR) Cell provided already belongs to a grid. This operation is not valid.
}

上述尝试是将linkLabel添加到第一个单元格而不是该列中的所有单元格
当我调试我的代码时,我得出结论,在将linkLabel添加到第一个单元格之后我在上面的代码中提到了异常错误,这使得代码无法正常运行。

请给我任何建议,我该怎么办?

编辑:虽然这不是正确的方法,但我通过编写以下代码给列单元格看起来像Linklabel

            foreach (DataGridViewRow row in dgvMain.Rows)
            {
                row.Cells[1].Style.Font = new Font("Consolas", 9F, FontStyle.Underline);
                row.Cells[1].Style.ForeColor = Color.Blue;
            }

现在问题是我不能将Hand像光标一样添加到唯一的列单元格(对于LinkLabels可见)。反正有没有实现它? (我需要回答这两个问题,主要是第一个问题)。

2 个答案:

答案 0 :(得分:5)

当我改变细胞类型时,这就是我一直在做的事情。 使用“也尝试过”的循环并更改:

dgvMain.Rows[intCount].Cells[0] = lnkCell;

要:

foreach (DataGridViewRow r in dgvMain.Rows)
  {
      DataGridViewLinkCell lc =  new DataGridViewLinkCell();
      lc.Value = r.Cells[0].Value;
      dgvMain[0, r.Index] = lc;
  }

第二个问题: 将dgvMain事件的CellMouseLeave和CellMouseMove设置为以下内容。

private void dataGridView1_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        this.Cursor = Cursors.Default;
    }
}

private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
{
    if (e.ColumnIndex == 1)
    {
        this.Cursor = Cursors.Hand;
    }
}

答案 1 :(得分:2)

您需要为每个“链接”单元格分配DataGridViewLinkCell的新实例。 Firt将链接的单元格类型更改为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);
    }
}