3

在我的项目中,我正在填充dataGridViewfrom dataSet(绑定DataGridViewto 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 可见)。有没有办法实现它?(我需要回答这两个问题,主要是第一个)。

4

2 回答 2

6

这就是我在更改单元格类型时一直在做的事情。使用您的“也尝试过”循环并更改:

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;
    }
}
于 2012-11-02T09:53:29.533 回答
2

您需要为每个“链接”单元格分配一个DataGridViewLinkCell实例。首先将作为链接的单元格的类型更改为 a 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);
    }
}
于 2013-04-22T12:11:02.600 回答