【问题标题】:Problems editing multiline textbox during runtime vb.net在运行时 vb.net 期间编辑多行文本框的问题
【发布时间】:2011-05-01 08:03:28
【问题描述】:

我是一名没有太多 vb.net 经验的大学生,在个人项目上需要一些帮助。我正在尝试增加多行文本框控件的高度,以便在运行时插入多行。按回车后,我想在文本框中换行。此外,同时我试图在通过按 Enter 创建的每个文本框行旁边生成一个组合框。这是我到目前为止的代码:

Private Sub ThisTextBox_keypress(ByVal sender As System.Object, ByVal e As KeyPressEventArgs) Handles ThisTextBox.KeyPress

    Dim TextboxLine As String() = ThisTextBox.Text.Split(vbNewLine)
    Dim Linecount As Integer = TextboxLine.Count
    If e.KeyChar = Chr(Keys.Enter) Then
       Me.ThisTextBox.Height = TextRenderer.MeasureText(" ", Me.ThisTextBox.Font).Height * _ Linecount 
       For Each Item In TextboxLine
            Dim newCombobox = New ComboBox()
            Me.Controls.Add(newCombobox)
            newCombobox.Items.Insert(0, "Item 1")
            newCombobox.Items.Insert(1, "Item 2")
            newCombobox.Items.Insert(2, "Item 3")
            newCombobox.Items.Insert(3, "Item 4")

            newCombobox.Location = New System.Drawing.Point(108, 69+=27)
            newCombobox.Size = New System.Drawing.Size(92, 21)

        Next
    End If


End Sub

问题是文本框的高度随着我输入的每个字符而增加,当我按下回车键时,控件高度以奇怪的增量增加,这与文本字体 * 行数无关。此外,我的代码可能与如何在运行时创建组合框并将其设置到特定位置相去甚远,但希望您能够看到我想要做什么。提前致谢。

【问题讨论】:

    标签: vb.net text combobox system.drawing


    【解决方案1】:

    有趣的问题。

    以下代码几乎可以实现您想要的,但是在每个文本行旁边放置一个组合框会导致问题,因为没有足够的空间使组合框足够高。

    Private Sub ThisTextBox_keypress(ByVal sender As System.Object, ByVal e As KeyPressEventArgs) Handles ThisTextBox.KeyPress
        Static previousLineCount = 0
        Dim LineCount As Integer = ThisTextBox.Lines.Count
        If LineCount > previousLineCount Then
    
            Dim lineHeight As Integer = TextRenderer.MeasureText(" ", Me.ThisTextBox.Font).Height
            ThisTextBox.Height = lineHeight * LineCount + 10
            For Each Item In ThisTextBox.Lines
                Dim newCombobox = New ComboBox()
                Me.Controls.Add(newCombobox)
                newCombobox.Items.Insert(0, "Item 1")
                newCombobox.Items.Insert(1, "Item 2")
                newCombobox.Items.Insert(2, "Item 3")
                newCombobox.Items.Insert(3, "Item 4")
    
                newCombobox.Location = New System.Drawing.Point(ThisTextBox.Left + ThisTextBox.Width, ThisTextBox.Top + (LineCount) * lineHeight - 12)
                newCombobox.Size = New System.Drawing.Size(92, lineHeight)
    
            Next
        End If
    End Sub
    

    我不知道有什么方法可以改变组合框控件的高度(如果可以的话,这里的其他人可能知道)但无论如何它看起来会很有趣。

    您还可以考虑使用 RichTextBox 控件并更改行距。

    希望上面的代码无论如何都能帮助您入门。

    【讨论】:

    • 谢谢,这非常有帮助,我会对其进行调整,以防止组合框控件在文本框中添加的每一行相互重叠。我什至可能只是将输入法从文本框更改为其他内容。谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-03-20
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多