【问题标题】:Align data in listBox对齐列表框中的数据
【发布时间】:2013-06-04 04:00:11
【问题描述】:

我通过以下代码将数据库加载到列表框中:

using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
        {
            myDatabaseConnection.Open();
            using (SqlCommand SqlCommand = new SqlCommand("Select ID, LastName from Employee", myDatabaseConnection))
            {
                SqlDataReader dr = SqlCommand.ExecuteReader();
                while (dr.Read())
                {
                    listBox1.Items.Add((string)dr["LastName"] + "    " + dr["ID"]);
                }
            }
        }

结果:

如何在listbox中这样对齐数据?

【问题讨论】:

标签: c# winforms ado.net listbox text-alignment


【解决方案1】:
while (dr.Read())
{
    listBox1.Items.Add((string)dr["LastName"] + "    " + dr["ID"],HorizontalAlignment.Right);
}

【讨论】:

  • 正确格式化您的代码,并可能添加一些解释
【解决方案2】:
using (SqlConnection myDatabaseConnection = new SqlConnection(myConnectionString.ConnectionString))
    {
        myDatabaseConnection.Open();
        using (SqlCommand SqlCommand = new SqlCommand("Select ID, LastName from Employee", myDatabaseConnection))
        {
            SqlDataReader dr = SqlCommand.ExecuteReader();
            while (dr.Read())
            {
                int lastNameLength = dr["LastName"].Length;
                int idLength = dr["ID"].Length;
                int numberOfSpaces = 30 - lastNameLength - idLength;
                string spaces = string.Empty;
                for (int i = 0; i < numberOfSpaces; i++)
                {
                    spaces = spaces + " "; 
                }                    
                listBox1.Items.Add((string)dr["LastName"] + spaces + dr["ID"]);
            }
        }
    }

这应该适合你。请注意“int numberOfSpaces = 30 - lastNameLength - idLength;”行中的 30,30 只是一个硬编码值,用于表示文本框中单行可以容纳的字符数。您也可以使用该号码或从您的文本框中输入它。但是这个方法现在应该将姓氏设置在框的左侧,id 应该固定在框的右侧。我希望这会有所帮助。

问候,

凯尔

【讨论】:

  • 不包含“Lenght”的定义,并且找不到接受“object”类型的第一个参数的扩展方法“Lenght”
【解决方案3】:

我认为您应该将数据添加到 dataGridView 组件中并使用表事件。

阅读this有关 Datagridview 的文章,根据您的描述,它是您所需要的

【讨论】:

    猜你喜欢
    • 2013-06-04
    • 2012-06-17
    • 2018-06-02
    • 2016-06-15
    • 2012-10-10
    • 2018-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多