Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add link label to DataGridView cell or column which is binded to DataSet

In my project, I'm filling the dataGridView from dataSet (binding the DataGridView to DataSet). The first column in dataGridView must be LinkLabels which I'm trying to get in the below code.

dgvMain.DataSorce = ds.Tables[0];

I tried: (not working)

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.
}

also tried

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.
}

The above attempts are adding linkLabel to the first cell only not all the cells in that column
When I debugged my code, I concluded that after adding the linkLabel to the first cell exception error is coming which I mentioned in the above code, which is making the code not to run properly.

Please give me any suggestions, what should I do?

EDIT: Though it is not the correct way but I gave the column cells a look like Linklabel by writing the below code:

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

Now the problem is that I cant add Hand like cursor to the only column cells(which is visible for LinkLabels). Is there anyway to achieve it? (I need answer for both questions, mainly the first one).

like image 621
Mr_Green Avatar asked Nov 14 '25 18:11

Mr_Green


1 Answers

This is what I've been doing when I'm changing type of the cell. Use your "also tried" loop and change:

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

To:

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

Second Question: Set the CellMouseLeave and CellMouseMove of the dgvMain events to the following.

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;
    }
}
like image 145
WozzeC Avatar answered Nov 17 '25 10:11

WozzeC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!