LuckyLuke82 LuckyLuke82 - 2 months ago 15
Vb.net Question

Custom Textbox Zoom - Return text to active datagridview cell?

I have 2 Datagridview controls in same form. Each Datagrid has some columns where user will write long texts, so I designed form with RichTextBox that opens when user double-clicks these columns to enlarge text-entry. Code works, but I want to use same form for both Datagrids, so I should somehow return text to active datagridview cell. Here is my code (for Datagridview1):

TextZoomForm:

Public Class TextZoomForm

Public OpenedForm1 As New Form1
Private Sub RichTextBox1_DoubleClick(sender As Object, e As EventArgs) Handles RichTextBox1.DoubleClick

OpenedForm1.DataGridView1.CurrentCell.Value = RichTextBox1.Text
OpenedForm1.Label24.Focus()
Me.Close()

End Sub

Private Sub TextZoom_Load(sender As Object, e As EventArgs) Handles Me.Load
RichTextBox1.Text = OpenedForm1.DataGridView1.CurrentCell.Value

End Sub

End Class


DataGridView1_CellMouseDoubleClick in Form1:

Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick

If e.ColumnIndex = 1 Then

Dim cp = Cursor.Position
cp.Y += CInt(Cursor.Size.Height * (-0.5))
cp.X += CInt(Cursor.Size.Width * 0.8)

Dim f As New TextZoomForm()
f.OpenedForm1 = Me
f.Show()
f.Location = New Point(cp)

End If

End Sub


Any ideas on how to return text to active datagridview cell?

Answer

Change your zoomed form so that it doesn't know where its data comes from. Instead the control using it will pass the data.

Public Class TextZoomForm

    Public Property ZoomedText As String
        Get
            Return RichTextBox1.Text
        End Get
        Set(value As String)
            RichTextBox1.Text = value
        End Set
    End Property

    Private Sub RichTextBox1_DoubleClick(sender As Object, e As EventArgs) Handles RichTextBox1.DoubleClick
        Me.Close()
    End Sub

End Class

To call the form change your code to the following:

Private Sub DataGridView1_CellMouseDoubleClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDoubleClick

...

            Dim f As New TextZoomForm()
            f.ZoomedText = DataGridView1.CurrentCell.Value
            f.ShowDialog()
            'Great breakpoint location.
            DataGridView1.CurrentCell.Value = f.ZoomedText
            Label24.Focus()
....

    End Sub

Using ShowDialog prevents the user from changing the current cell part way through your call.

If you need it modeless then you should:

  • store the cell that the user has selected
  • handle the FormClosing event.
  • Test the DialogResult to make sure the user pressed ok
  • write the data back to the stored cell.
Comments