Search code examples
vb.netdatagridviewdatagridviewlinkcolumn

HOW TO: Change datagridview LinkColumn Text when clicked


I'm having a problem in my DataGridViewLinkColumn. When specific columnIndex clicked, I want to change the link column text. (please see example below) enter image description here

In example above, I want to change the text(the highlighted one) that is clicked to SAVE.
NOTE: the changing must be done only in specific row and column index

I used datagridViewColumn and here's my code: (link column displays when bind in datatable then display to datagrid.)

        Dim da As New SqlDataAdapter("SELECT DateReq AS [Date Requested],NoHrs AS [# OT Hrs.],status,approved_by FROM tableName" _
            & "WHERE requested_by='" & lbluserid.Text & "'" _
            & " ORDER BY date_request ASC", Constr)
        Dim dt As New DataTable

        ds.Clear()
        da.Fill(dt)


        dg.DataSource = dt

        dg.Columns.Add(lnkEdit)
        lnkEdit.HeaderText = ""
        lnkEdit.Name = "edit"
        lnkEdit.Text = "Edit"
        lnkEdit.UseColumnTextForLinkValue = True
        dg.Columns(4).Width = 45
        dg.Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

        dg.Columns.Add(lnkCancel)
        lnkCancel.HeaderText = ""
        lnkCancel.Name = "cancel"
        lnkCancel.Text = "Cancel"
        lnkCancel.UseColumnTextForLinkValue = True
        dg.Columns(5).Width = 45
        dg.Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

Solution

  • Just handle the CellContentClick event, get the right cell and set it's value:

    ' If your DataGridView is named dataGridView1: '
    Private Sub dataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataGridView1.CellContentClick
        dataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = "Saved"
    End Sub
    

    Note that your problem is that a DataGridViewLinkCell either displays it's Value (when UseColumnTextForLinkValue == false), or it displays the Text of it's DataGridViewLinkColumn (when UseColumnTextForLinkValue == true).

    So if you want to change the text of the link at runtime you'll have to set UseColumnTextForLinkValue = false, and fill the cells beforehand with the text Edit, e.g. something like:

    For Each row in dg.Rows
        row(your_link_column).Value = "Edit"
    Next