How can I refer to the name of the control which is saved in the String

tovia schlesinger 241 Reputation points
2021-02-09T22:50:32.087+00:00

I'd like to cut and paste from one control to the other.
However, the name of the control is saved in a String.

Dim ctrl As Control
ctrl = CntrlNm
CntrlNm is a String which contains the name of the control.
The following error message is generated.
"BC30068 Expression is a value and therefore cannot be the target of an assignment"
How can I refer to the name of the control which is saved in the String without getting an error message?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,628 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 113.8K Reputation points
    2021-02-10T07:46:41.547+00:00

    To get the control by name (a textbox, for example), check this sample:

    Dim CntrlNm = "textBox1"
    Dim textbox As TextBox = CType(Controls.Find(CntrlNm, True)(0), TextBox)
    

    To get a generic control:

    Dim ctrl As Control = Controls.Find(CntrlNm, True)(0)
    
    0 comments No comments

  2. Xingyu Zhao-MSFT 5,356 Reputation points
    2021-02-11T09:16:30.073+00:00

    Hi @tovia schlesinger ,

    You can consider using the following extension method to clone the control. (code from here)

    Module ControlExtensions  
        <Extension()>  
        Function Clone(Of T As Control)(ByVal controlToClone As T) As T  
            Dim controlProperties As PropertyInfo() = GetType(T).GetProperties(BindingFlags.[Public] Or BindingFlags.Instance)  
            Dim instance As T = Activator.CreateInstance(Of T)()      
            For Each propInfo As PropertyInfo In controlProperties     
                If propInfo.CanWrite Then  
                    If propInfo.Name <> "WindowTarget" Then propInfo.SetValue(instance, propInfo.GetValue(controlToClone, Nothing), Nothing)  
                End If  
            Next  
            Return instance  
        End Function  
    End Module  
    

    Hope it could be helpful.
    Besides, if you need further assistance, please let me know.

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments