Select new user when clicking "Add"

Viewed 79

I have the following method. I am trying to make it so that when a user clicks the 'Add' button, the newly added user is selected in the name comboBox.

private void AddUser()
{
    string userQueryString = "SELECT[User_ID], [User_First_Name], [User_Surname] FROM[EquipmentTracker].[dbo].[Users]";
    SqlConnection conn = new SqlConnection(constring);
    SqlCommand commandRecipient = new SqlCommand(userQueryString, conn);
    conn.Open();

    SqlDataReader reader = commandRecipient.ExecuteReader();

    while (reader.Read())
    {
        User addUser = new User();
        addUser.userID = (int)reader["User_ID"];
        addUser.userName = (string)reader["User_First_Name"] + " " + (string)reader["User_Surname"];
        comboRecipient.Items.Add(addUser);
    }
}

Previously, before I created a method to prevent re-writing code, this is how I had this working:

private void btnNewUser_Click(object sender, EventArgs e)
{
    Form2 newUser = new Form2();
    if(newUser.ShowDialog() == DialogResult.OK)
    {
        SqlConnection conn = new SqlConnection(constring);
        conn.Open();
        SqlCommand commandRecipient = new SqlCommand("SELECT [User_ID], [User_First_Name], [User_Surname] FROM [EquipmentTracker].[dbo].[Users]", conn);
        comboRecipient.Items.Clear();

        using (SqlDataReader reader = commandRecipient.ExecuteReader())
        {
            while (reader.Read())
            {
                int recipientID = (int)reader["User_ID"];
                string recipient = (string)reader["User_First_Name"] + " " + (string)reader["User_Surname"];
                comboRecipient.Items.Add(recipientID);
                comboRecipient.Items.Add(recipient);
                Console.WriteLine(String.Format("{0}", reader[0]));
            }
        }
        comboRecipient.SelectedItem = newUser.newUser;
    }
}

Now, I am just calling the method here:

private void btnNewUser_Click(object sender, EventArgs e)
{
    Form2 newUser = new Form2();
    if(newUser.ShowDialog() == DialogResult.OK)
    {
        AddUser();
        comboRecipient.SelectedItem = newUser.newUser;
    }
}
2 Answers

You need to configure the ComboBox to use the right properties from the User objects that you are feeding in.

Here is how to do it programmatically, e.g. in the Form Load event:

comboRecipient.DisplayMember = "userName";  
comboRecipient.ValueMember = "userID";

Or you can set it in the properties of comboRecipient in the Form Designer.

Your question is a little confusing. You mention adding a new user but you never actually add a new user. Instead, AddUser just loads a number of user records from the database and adds them to the combobox and selects each one in turn. Whichever order the records come out from the database in determines which one gets selected last.

The fix is three-fold:

  1. Clear the combobox item list prior to re-populating it:

comboRecipient.Items.Clear();

As it stands, each time you call AddUser you re-add all the users again.

  1. Order the users in your query so that the newest one is always last:

SELECT [User_ID], [User_First_Name], [User_Surname] FROM [EquipmentTracker].[dbo].[Users] ORDER BY [User_ID]

This assumes that User_ID is an auto-incrementing field. If you have a CreationDate column, you can use that instead.

  1. Select the last item in the combobox once you've added all items:

Instead of:

comboRecipient.SelectedItem = newUser.newUser;

Use:

    comboRecipient.SelectedIndex = comboRecipient.Items.Count - 1

This will select the last item in the combobox as long as there are items in the combobox. If there are no items then the result of the calculation will be -1 which is a valid index for a combobox (even when using databinding).

You may also notice your combobox items don't appear correctly. You can correct this by setting:

comboRecipient.DisplayMember = "userName";
comboRecipient.ValueMember = "userID";

This can be set anywhere but it's worth setting it up either in the constructor or the Load event handler.

Related