我试图用组合框来改变字体大小。 问题是@runtime我得到一个没有价值的错误。 在表单加载上我将selectedindexitem设置为3
mycode的:
更新:仅当我使用数字设置整数值时才有效...我希望能够使用comboboox1更改它。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboBox1.SelectedIndex = 2
End Sub
Dim myFontSize As Integer = 120
Dim myFont As New Font("Arial", myFontSize, FontStyle.Bold Or FontStyle.Italic)
Dim Loc As Point
Dim Pxy As Point
Private Sub PictureBox1_MouseMove(sender As Object, e As MouseEventArgs) Handles PictureBox1.MouseMove
txtButton.Text = MouseButtons.Left
If e.Button = MouseButtons.Left Then
Loc = e.Location
Me.PictureBox1.Invalidate()
End If
End Sub
Private Sub PictureBox1_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles PictureBox1.Paint
Dim pt As Point = PictureBox1.PointToClient(Control.MousePosition)
e.Graphics.DrawString(txtA.Text, myFont, Brushes.Black, pt.X, pt.Y)
End Sub
Private Sub ComboBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles ComboBox1.KeyPress
Dim KeyAscii As Integer = Asc(e.KeyChar)
Select Case KeyAscii
Case 8, 27, 48 To 57, 9
Case Else
KeyAscii = 0
End Select
If KeyAscii = 0 Then
e.Handled = True
Else
e.Handled = False
End If
End Sub
也许并不重要,但我在Combobox_KeyPress上只有代码才能允许数字。任何帮助或指向,我是正确的直线吗?
答案 0 :(得分:0)
如果我理解得很好,问题是在表单加载事件中它会引发异常,因为组合框中没有选定的项目吗?
此外,您在哪里尝试运行该代码?。
无论如何,你可以编写一个条件来确保有一个选定的项目,然后避免该异常:
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) _
Handles ComboBox1.SelectedIndexChanged
Dim cb As ComboBox = DirectCast(sender, ComboBox)
If cb.SelectedItem IsNot Nothing Then
Using font As New Font("Arial", Convert.ToInt32(cb.Text),
FontStyle.Bold Or
FontStyle.Italic)
otherControl.Font = font
End Using
End If
End Sub
答案 1 :(得分:0)
我得到了工作!
Dim myFontSize As Integer
Integer.TryParse(ComboBox1.Text, myFontSize)
Dim myFont As New Font("Arial", myFontSize, FontStyle.Bold Or FontStyle.Italic)
这就是诀窍。
答案 2 :(得分:-1)
您应该从FontSize
获取ComboBox.SelectedItem
而不是来自父级。此外,“FontSize”已经是字符串中的变量,因此您应该将自定义变量命名为其他内容:
Dim MyFontSize As Integer = CInt(myComboBox.SelectedItem)
Dim myFont As New Font("Arial", MyFontSize, FontStyle.Bold Or FontStyle.Italic)