Winform DataGridViewLinkColumn ReadOnly property not working

371 Views Asked by At

In my VS2015 Winform app, there is one DataGridView control bound to a BindingSource that is bound to a SQL database. The Grid has four columns: ID, URL, Name, Type. The URL column is DataGridViewLinkColumn whose ReadOnly property, by default, is set to False. I can edit the Name and Type columns but URL columns shows as ReadOnly. Why? How can I make URL column editable?

1

There are 1 best solutions below

0
On

As Reza stated:

DataGridViewLinkColumn is not editable.

Therefore, to edit a cell in such a column you'll have to convert it to a DataGridViewTextBoxCell as needed. For instance, if I have subscribed to DataGridView.CellContentClick to handle clicking on a link, then I would handle CellDoubleClick for the cell conversion:

private void DataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex] == this.dataGridView1.Columns["URL"])
    {
        this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex] = new DataGridViewTextBoxCell();
        this.dataGridView1.BeginEdit(true);
    }
}

Once you've entered your value and left the cell, you should then use CellValidated to verify that the new value is a URI before converting the cell back to a DataGridViewLinkCell:

private void DataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex] == this.dataGridView1.Columns["URL"])
    {
        DataGridViewCell cell = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];

        if (Uri.IsWellFormedUriString(cell.EditedFormattedValue.ToString(), UriKind.Absolute))
        {
            cell = new DataGridViewLinkCell();
        }
    }
}

Caveat:

  • This only worked for me when the data for the "URL" column were strings and thus after binding, the column defaulted to a DataGridViewTextBoxColumn - forcing a manual conversion to link cells to begin with:

    private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        foreach (DataGridViewRow r in dataGridView1.Rows)
        {
            if (Uri.IsWellFormedUriString(r.Cells["URL"].Value.ToString(), UriKind.Absolute))
            {
                r.Cells["URL"] = new DataGridViewLinkCell();
            }
        }
    }
    
  • Setting up the "URI" column as a DataGridViewLinkColumn from the beginning allowed for the conversion of cells to TextBox type successfully. But when converting back to link cells, debugging showed the conversion to happen, but the cell formatting and behavior failed.