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

Mr_*_*een 3 .net c# datagridview winforms

在我的项目中,我正在填充dataGridViewfrom dataSet(绑定DataGridViewDataSet).第一列dataGridView必须是LinkLabels我想在下面的代码中得到的.

dgvMain.DataSorce = ds.Tables[0];
Run Code Online (Sandbox Code Playgroud)

我试过:( 不工作)

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.
}
Run Code Online (Sandbox Code Playgroud)

也试过了

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.
}
Run Code Online (Sandbox Code Playgroud)

上面的尝试只是添加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;
            }
Run Code Online (Sandbox Code Playgroud)

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

Woz*_*zeC 5

这是我在改变细胞类型时一直在做的事情.使用"也尝试过"的循环并更改:

dgvMain.Rows[intCount].Cells[0] = lnkCell;
Run Code Online (Sandbox Code Playgroud)

至:

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

第二个问题:将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;
    }
}
Run Code Online (Sandbox Code Playgroud)