[.net] Can't do selectionstart from outside a form???

Started by
4 comments, last by benryves 15 years, 9 months ago
Hi, I am adding a find feature to my notepad I coded in vb.net, but it won't let me do selectionstart and selectionlength from outside of the main form.


   Private Sub btnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFind.Click


        str = Form1.TextBox1.Text
        strfind = txtFind.Text

        If str.Contains(strfind) Then

            Form1.TextBox1.SelectionStart = CStr(str.IndexOf(strfind))
            Form1.TextBox1.SelectionLength = CStr(strfind.Length)

            btnFindNext.Enabled = True
        End If
    End Sub

Advertisement
What's the exact error message?

I assume Form1 is the name of a Form based class and that TextBox1 is a private instance field of Form1. In this case:
1.) You cannot access instance members without an instance of the defining class. The btnFind_Click method needs to have access to an instance of Form1 somehow. For example you can pass the Form1 instance as a constructor argument to the class that defines btnFind_Click. Or you can define a property with a setter to accept the instance.

2.) You won't be able to access private members from outside the class. In your case, btnFind_Click will not have access to TextBox1 if btnFind_Click is not a member of Form1. You can provide a public property on Form1 that returns the TextBox instance.

3.) Generally it would be a better design if Form1 would not expose its controls. A better approach would be to have one property that returns the text in the text box and maybe have a method SelectText(start as Int32, length as Int32) that sets the selection for the text box.

Regards,
Andre
Andre Loker | Personal blog on .NET
Hi,

btnFind_Click actually does have access to textbox1. I can edit and delete text from the find form. The problem is, I can't select text until the main form has focus again.
Set the HideSelection property of the textbox to False.

Former Microsoft XNA and Xbox MVP | Check out my blog for random ramblings on game development

awesome, thanks. Now if I could only figure out how to make it scroll down to the selected text, I would be all set.
TextBoxBase.ScrollToCaret()

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

This topic is closed to new replies.

Advertisement