Click here to Skip to main content
15,891,136 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my c# application there is a combo box listing 'customer names' which is placed in the MainForm .There is a button for adding new customers when clicking on the button another form opens and we need to save customer details. After this i want to reload the 'MainForm' for the combobox to include the new name or the combobox to display the new name .


thanks in advance.
Posted
Updated 25-Dec-17 3:04am
Comments
BulletVictim 27-Aug-13 8:13am    
Ok the fastest way I can think to do this is something like this.
on the MainForm button click to add new user:
AddForm frmAdd = new AddForm();
this.Hide();
frmAdd.ShowDialog();
try{
this.Show();
}

Then on the button to save the user or return to the MainForm:
MainForm frmMain = new MainForm();
this.Hide();
frmMain.ShowDialog();
try{
this.Show();
}
This basically closes the MainForm while you are adding a new customer and then when that form closes it opens the a new MainForm and runs all the code again so it should re-populate your combobox assuming it is populated in the form load of the MainForm.
BillWoodruff 27-Aug-13 18:55pm    
You really need to think through the effects of running this code. For one thing, you will create possible multiple instances of MainForm, and each new instance of MainForm will no have no access to any information created on the previous instances of MainForm. You will also never be able to pass any information entered in 'AddForm into any instance of MainForm.
BillWoodruff 27-Aug-13 19:02pm    
The essence of the scenario here is how to pass information from one Form to another, one of the most frequently asked and answered questions here. There are several options.

In this case, we are missing two very important pieces of information:

1. in your Main Form, when the user selects an existing entry in the ComboBox: is anything displayed on the Main Form ? If so, what is displayed, and in what type of Control is whatever is displayed: displayed ?

2. when the user creates a new entry, and fills out the fields (we assume) in the new Form, and (we assume) you validate the entries, and the user is then allowed to close the entry Form: how do you plan to store this new "entity" you have created ? Into what type of Collection, or List of something-or-other: into a Database ?

Depending on your goals, these two questions, can have a great impact on your design, and if you answer them clearly, I'll be happy to respond further with a solution.
RizwanShaikh 4-Aug-15 1:01am    
but do not open new form open.....
old form reload .....
how do

You can use delegates to achieve this functionality. Using delegates in such a scenario is pretty common. To know more about delegates you can visit the following links:


C# Delegates: Step by Step[^]
http://msdn.microsoft.com/en-us/library/ms173171%28v=vs.90%29.aspx[^]
http://msdn.microsoft.com/en-us/library/vstudio/ms173172.aspx[^]
 
Share this answer
 
C#
// This goes in your Main form
private void BtnAddNewCustomer_Click(object sender, EventArgs e)
{ // When the user clicks on the button
    CreateUserForm form = new CreateUserForm();
    // TODO: do more stuff with the form
    if(form.ShowDialog() == DialogResult.OK)
    { // User clicked ok on the form and user is now saved
        // TODO: Reload your combo box
    }
    // Safe to close form now
    form.Close();
    form.Dispose();
}


// This goes in CreateUserForm.cs code
private void BtnCreateUser_Click(object sender, EventArgs e)
{
    // TODO: Validate/Save your data here
    DialogResult = DialogResult.OK;
    /* Do not close from this form, 
     * otherwise everything gets disposed of
     * and you will loose data
     */
    Hide();
}
 
Share this answer
 
Comments
RizwanShaikh 4-Aug-15 1:07am    
i wana do not open new form ,,,,,,,
reload open old form....
how do
Praveen_P 6-Aug-15 9:05am    
if you don't want to open new form then after saving rebind the dropdown once again
This could serve you for some more scenarios.

Encapsulate you customer data in one class (eg. MyCustomerData) with all the properties and fields needed for holding the information which is relevant to your application (MyCustomerData.cs).
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ComboBoxUpdate
{
    /// <summary>
    /// Customer Data Encapsulation
    /// </summary>
    public class MyCustomerData
    {
        /// <summary>
        /// Field for holding the Name
        /// </summary>
        private string m_Name;

        /// <summary>
        /// Gets or Sets the customer Name
        /// </summary>
        public string Name
        {
            get { return m_Name; }
            set { m_Name = value; }
        }


        /// <summary>
        /// Contructor
        /// </summary>
        /// <param name="Name">The Name of the Customer</param>
        public MyCustomerData(string Name)
        {
            this.Name = Name;
        }
    }
}


Create one (let's say) MyCustomerDataEditor form with one constructor that takes one instance from your MyCustomerData class. Of course you need to add all the user input validation logic that ensures data correctness, enables|disables the 'Accept' button after changes validation (etc.).
MyCustomerDataEditorFrm.cs

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ComboBoxUpdate
{
    public partial class MyCustomerDataEditorFrm : Form
    {
        private MyCustomerData m_Customer;


        public MyCustomerData Customer
        {
            get { return m_Customer; }
            set 
            {
                m_Customer = value;
                ValidateEditors();
            }
        }


        public MyCustomerDataEditorFrm( MyCustomerData Customer )
        {
            m_Customer = Customer;

            InitializeComponent();

            this.Customer = Customer;
        }


        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            ValidateEditors();
        }


        private void ValidateEditors()
        {
            // Simple validation, only accept not empty name.
            button1.Enabled = !string.IsNullOrEmpty(textBox1.Text);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            // Apply changes;
            m_Customer.Name = textBox1.Text;
        }
    }
}


Declare some kind of list for holding the MyCustomerData instances list in your main form:
C#
List<mycustomerdata> m_MyCustomers = new List<mycustomerdata>()</mycustomerdata></mycustomerdata>


In your main form populate the list with valid data from your database. Let's suppose you have one method called GetMeTheDataFromTheDataBase()hat retrieves that data.
C#
m_MyCustomers.AddRange( GetMeTheDataFromTheDataBase())


You may configure the ComboBox so the text it displays is the CustomerName property (provided that you declared it in the MyCustomerData class).

The main form could end up like this:

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ComboBoxUpdate
{
    public partial class Form1 : Form
    {
        private List<mycustomerdata> m_Customers;

        public Form1()
        {
            m_Customers = new List<mycustomerdata>();

            InitializeComponent();

            comboBox1.DisplayMember = "Name";
            LoadCustomers();
            UpdateCustomersComboBox();
        }


        /// <summary>
        /// Update the combobox items from the customers list.
        /// </summary>
        private void UpdateCustomersComboBox()
        {
            foreach (MyCustomerData Customer in m_Customers) 
            {
                if (comboBox1.Items.IndexOf(Customer) < 0) 
                    comboBox1.Items.Add(Customer);
            }

            UpdateUIControls();
        }


        /// <summary>
        /// Populate the local copy of the customers list
        /// </summary>
        private void LoadCustomers()
        {
            m_Customers.AddRange( new MyCustomerData[] {
                new MyCustomerData( "John Doe" ),
                new MyCustomerData( "Jane Doe" )
            });
        }


        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            UpdateUIControls();
        }


        /// <summary>
        /// Update the state of all relevant controls
        /// </summary>
        private void UpdateUIControls()
        {
            button2.Enabled = (comboBox1.SelectedIndex >= 0);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // Simply add some data. Here you should do 
            MyCustomerDataEditorFrm Dlg = new MyCustomerDataEditorFrm(new MyCustomerData( "Joe's Brother!" ));
            if (Dlg.ShowDialog(this) == DialogResult.OK)
            {
                m_Customers.Add(Dlg.Customer);
                UpdateCustomersComboBox();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MyCustomerData Customer = comboBox1.SelectedItem as MyCustomerData;

            if (DialogResult.Yes != MessageBox.Show(this, "Sure to remove " + Customer.Name, "Remove Customer", MessageBoxButtons.YesNo, MessageBoxIcon.Warning))
                return;

            m_Customers.Remove(Customer);
            comboBox1.Items.Remove(Customer);

            UpdateUIControls();
        }
    }
}
</mycustomerdata></mycustomerdata>


One more thing, the components in the main form are the combobox (combobox1), one "Add New" button (button1) and one "Remove" button (button2).

I didn't see the way to attach the sample project/code, but if you need it i can e-mail it to you.

Hope it helps you some how.
 
Share this answer
 
v2
In Adding Customer Name Button Clear The Combobox like CmbName.items.clear(),
After Inserting A new name to data base reload all names from data base to combobox
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900