问题描述
我正在与我的列表框和列表框中的值搏斗一段时间,但我偶然发现了另一个问题.
I am wrestling with my listbox and values in the listbox for some time now and I stumbled across another problem.
我正在从我的 Access 数据库中获取数据(字段名称和值)并将它们显示在列表框中.我试图在字段名称右侧以相等的距离勾勒出字段名称的值(因此它们都在彼此下方).我正在尝试为此使用 PadLeft 功能,但由于某种原因,这并没有在彼此下方勾勒出它们.我认为这与字段名称的长度有关.
I am fetching data from my Access database (both the field names and the values) and displaying them in a listbox. I am trying to outline the values of the field names to the right of the field name on a equal distance (so they are all below each other). I am trying to use the PadLeft function for this but for some reason this doesn't outline them below each other. I think this has something to do with the Length of the field names.
我用这行代码得到的结果:
The result what i am getting with this line of code:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from Sparen WHERE Id=1";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
var columns2 = listBox6;
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
columns2.Items.Add(reader.GetName(i) + reader.GetValue(i).ToString().PadLeft(15));
}
}
connection.Close();
}
这是:
如您所见,这些值的轮廓并不低于彼此.似乎字段名称长度会影响填充计数.
As you can see the outlining of the values aren't below each other. It seems that the field name length affects the padding count.
所以我想我可以通过用字段名称的长度减去填充来解决这个问题,如下所示:
So I thought I could fix this by subtracting the padding with the length of the field name like this:
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
string query = "select * from Sparen WHERE Id=1";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
int x;
var columns2 = listBox6;
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
x = reader.GetName(i).Length;
columns2.Items.Add(reader.GetName(i) + reader.GetValue(i).ToString().PadLeft(15 - x));
}
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
结果如下:
正如您所见,新代码对大纲差异产生了一些影响,但它仍然没有达到预期的效果.轮廓仍然不相等(彼此下方).有人知道这里出了什么问题吗?
As you can see the new code has had some effect on the outlining difference but it still didn't do what it was supposed to. The outlining is still not equal (below each other). Anyone has an idea what goes wrong here?
推荐答案
要解决您的直接问题,只需在 ListBox 中使用固定宽度的字体:
To fix your immediate issue, just use a fixed-width font in the ListBox:
listBox1.Font = new Font(FontFamily.GenericMonospace, listBox1.Font.Size);
现在您的填充逻辑将按预期工作:
Now your padding logic will work as you expect:
请考虑汉斯的观点;检查已显示多列数据的控件,例如 ListView 或 DataGridView.
Consider Hans's point though; check into controls that already display multiple columns of data, like the ListView or a DataGridView.
这篇关于使用 PadLeft 函数在 C# 中同样概述列表框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!