1

I load the database in listbox by this code:

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"]);
                }
            }
        }

Result:

1

How to align the data like this in listbox?

2

Karlx Swanovski
  • 2,869
  • 9
  • 34
  • 67
  • `\t` should do the trick. http://stackoverflow.com/a/366126/227646 Another answer here: http://stackoverflow.com/a/4449167/227646 – kush Jun 07 '13 at 18:51

3 Answers3

1
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"]);
            }
        }
    }

This should work for you. Please note that the 30 in the line "int numberOfSpaces = 30 - lastNameLength - idLength;", the 30 is just a hard coded value for the number of characters that can fit on a single line in your text box. You can play with that number or pull in it from your text box too. But this method should now set the last name to left of the box and id should be pinned to the right of the box. I hope this helps.

Regards,

Kyle

kformeck
  • 1,703
  • 5
  • 22
  • 43
  • does not contain a definition for 'Lenght' and no extension method 'Lenght'accepting a first argument of type 'object' could be found – Karlx Swanovski Jun 08 '13 at 06:34
0

I think you should add your data in a dataGridView component and work with table events.

Read this article about Datagridview, up to your discription its what you need

Vahid
  • 354
  • 1
  • 3
  • 10
-1
while (dr.Read())
{
    listBox1.Items.Add((string)dr["LastName"] + "    " + dr["ID"],HorizontalAlignment.Right);
}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117