0

请参考以下图片:

Button.Text 硬编码 来自数据库的 Button.Text

所以左边的图像有一个硬编码的字符串,右边的图像有从 MSSQL 数据库中提取的数据。

下面的代码组成了这些按钮(它们是根据数据库表中的记录数量动态创建的)

    'Button 
Private Sub LoadUseraccount()

    'Connect to Database (from module1)
    connectSQL()

    'Setup DataAdapter with query
    Dim da As SqlDataAdapter
    da = New SqlDataAdapter("SELECT * from useraccounts", SQLConn)

    'Store results in temporary datatable
    Dim dt As DataTable
    dt = New DataTable()

    da.Fill(dt)

    Dim i As Integer

    'Create a button for every record shown in useraccount table.
    For i = 0 To dt.Rows.Count - 1
        Dim dr As DataRow = dt.Rows(i)
        Dim newbutton As New Windows.Forms.Button
        Dim dataString As String = CStr(dr.Item("username"))


        newbutton.Name = "btnButton" & i
        newbutton.Text = dataString '<========= This Line is where the button text is set
        newbutton.Top = 200 + i * 105
        newbutton.Left = 40

        newbutton.TextAlign = ContentAlignment.MiddleCenter

        newbutton.Height = 107
        newbutton.Width = 180

        Dim myFont As System.Drawing.Font
        myFont = New System.Drawing.Font("Arial", 20.25)
        newbutton.Font = myFont
        newbutton.ForeColor = Color.White
        newbutton.BackColor = Color.MidnightBlue

        Me.Controls.Add(newbutton)
    Next

    SQLConn.Close()

End Sub

所以图像中唯一的区别是文本设置在按钮上显示的内容,但是当字符串不是静态的时,对齐方式完全不正常。

我做错了什么或者我错过了什么让正确的图像格式与左边的图像相同?

干杯:-)

4

1 回答 1

0

我已经尝试了您的示例,但在将回车/换行添加到用于按钮文本的变量之前,我无法重现该问题。

因此,我假设您的数据包含一些无法打印的字符,这些字符会使您的输出不对齐。

一个简单的修复应该是

newbutton.Text = dataString.Trim()
于 2013-11-08T23:25:44.307 回答