Search code examples
c#visual-studiodouble-clicklistboxitems

How to use a double click event to click text in a listbox to make that text appear in a empty textbox


Hi I have created a booking facility and I want to allocate a customer to each booking. I have created a listbox which is generated with the names of the customers in the database. I want to be able to double click on one of the names and that name will appear in a textbox in the same form. Appreciate all help. Thanks

Here is the code which generates my customers

   public void getListOfAllCustomers()
    {
        SqlConnection conn = new SqlConnection(connectionString);
        try
        {
            conn.Open();

            str = "Select CustomerId, CustomerName from Customer";
            SqlCommand cmd = new SqlCommand(str, conn);
            SqlDataReader myReader = cmd.ExecuteReader();
            DataTable CustomerList = new DataTable();
            CustomerList.Columns.Add("CustomerId", typeof(string));
            CustomerList.Columns.Add("CustomerName", typeof(string));
            CustomerList.Load(myReader);
            LBcustomersavailable.ValueMember = "CustomerId";
            LBcustomersavailable.DisplayMember = "CustomerName";
            LBcustomersavailable.DataSource = CustomerList;
            LBcustomersavailable.BindingContext = this.BindingContext;
        }
        catch (Exception ex)
        {

            string filepath = AppDomain.CurrentDomain.BaseDirectory + "ErrorLog.txt";
            using (StreamWriter writer = new StreamWriter(filepath, true))
            {
                //Log error that occurred into a text file 
                writer.WriteLine("Message :" + ex.Message + "<br/>" + Environment.NewLine + "StackTrace :" + ex.StackTrace + "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            }
            MessageBox.Show("Error Message :" + ex.Message + Environment.NewLine + "An error has occurred. Try restarting your application and if this error keeps occuring please call our helpdesk");
        }
        finally
        {
            conn.Close();
        }

    }

Here is an image of the design


Solution

  • You need to bind a double click event to your list box.

    To do this, view the form in design mode, click on your list box and hit F4 to view the Properties window. Then click the "lightning Flash" symbol to bring up the events list. Choose DoubleClick, click in the box and hit enter. This should add the event binding for you.

    Below is a simple example.

    private void LBcustomersavailable_DoubleClick(object sender, EventArgs e)
    {
          if (((ListBox)sender).SelectedItem != null)
                txtName.Text = ((ListBox)sender).SelectedItem.ToString();
    }
    

    I've added a text box called txtName to show the entry clicked in the listbox.

    Hope that helps