您应该知道姓氏的确切最大长度(在您的表格中设计)并应用适当的长度,例如 + 10。这里我使用 50(最大长度)进行演示。
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(dr["LastName"].ToString().PadRight(50) + dr["ID"]);
}
}
}
抱歉,我没有测试它,但正如 rene 所说,使用固定宽度字体会有所帮助。但是我有另一个解决方案DrawItem
,这是不完整的,但可以让你开始,完成它我认为我们需要更多的测试和自定义代码:
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.Format("{0}\n{1}",dr["LastName"],dr["ID"]));
}
}
}
//DrawItem
//first, set listBox1.DrawMode = DrawMode.OwnerDrawFixed;
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
string[] ss = listBox1.Items[e.Index].ToString().Split(new char[]{'\n'});
Rectangle rect = new Rectangle(e.Bounds.Left, e.Bounds.Top, (int) (e.Bounds.Width * 0.5), e.Bounds.Height);
Rectangle rect2 = new Rectangle((int)(e.Bounds.Width * 0.5), e.Bounds.Top, e.Bounds.Width - (int)(e.Bounds.Width * 0.5), e.Bounds.Height);
StringFormat sf = new StringFormat() { Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center };
e.Graphics.DrawString(ss[0], listBox1.Font, new SolidBrush(listBox1.ForeColor), rect,sf);
e.Graphics.DrawString(ss[1], listBox1.Font, new SolidBrush(listBox1.ForeColor), rect2, sf);
}
正如我所说,这只是让您开始使用,而不是完整和完美的代码。例如,我使用列表框的 50% 宽度来绘制第一个“虚拟列”,其余的用于绘制第二个“虚拟列”。所以这是你定制它的一部分。