Monday, May 24, 2010

How to change a read-only property to a property that can be changed (Visual Basic 2005 Express)?

For example, the size, font family, etc. of Textbox1. The compiler keeps telling me they're read-only. How to make them changable?

How to change a read-only property to a property that can be changed (Visual Basic 2005 Express)?
You can in fact change Font properties at run-time. However, you cannot do it the same way as you did in Visual Basic 6.





In Visual Basic .NET, fonts are read-only at run-time — you cannot set the properties directly, but you can assign a new Font object:


_______________





' This next statement generates an error—property is read-only.


TextBox1.Font = Arial





' These next two statements are the correct way.





' Assign a Font object—Name and Size are required.


TextBox1.Font = New System.Drawing.Font("Arial", 10)





' Assign additional attributes.


TextBox1.Font = New System.Drawing.Font(TextBox1.Font, FontStyle.Italic)





' Note: The Answers Editor does not always properly display information that is placed within parentheses.


' It sometimes truncates the enclosed expression.





' Please replace the above truncated parameters with:


' TextBox1.Font, FontStyle.Italic





_______________________________
Reply:The values in the properties are members they are read only at run time; however, you can assign a new object of the property type to you control.


In order to change certain properties at run time you have to: 1) create an object of the type of the property. 2) make changes to the values. 3) then assign the new object to the control.


Here is a simple sample I wrote. On the click of the button the size and font of the text box changes. The size of the button also changes.





Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


Dim size As System.Drawing.Size


size = TextBox1.Size


size.Width = size.Width + 50


TextBox1.Size = size





size = Button1.Size


size.Height = size.Height + 200


Button1.Size = size





Dim f As System.Drawing.Font


f = New System.Drawing.Font("Comic Sans MS", 10, FontStyle.Bold)


TextBox1.Font = f


End Sub

graphics cards

No comments:

Post a Comment