简体   繁体   中英

how to store id and name in datagridview combox column

i am creating an windows form application.In the application created a form for employees attendance .

The form contains Datagridview and there are two columns one for employees(which is combobox column ) and another is checkbox columns(whether employee is present or absent). columns i am creating programmatically.

i have a list of employee object (which contain employee name and ID).

i want to store name and id of the employee in datagridview combobox column so that i can save attendance details using employee id(not based on employees name) so how can is store employees name and id(both) in datagrdiview combobox column .

i want to display employees name in combobox column,not employees id.

so please provide solution.

One way that you can achieve this is by adding the object to the combobox items (Combobox.Items.Add(EmployeeObject)) and after that setting the DispayMember property of the control(ComboBox) to the name property(or member). The next example creates an list of 10 Johns with unique ids and gets the ID of current selected item.

  public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 10; i++)
        {
            ComboboxItem item = new ComboboxItem("John", i);
            comboBox1.Items.Add(item);



        }
        comboBox1.DisplayMember = "Name";
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboboxItem item = (ComboboxItem)comboBox1.SelectedItem;
        MessageBox.Show(item.ID.ToString());
    }

Also checkout http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.items.aspx

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM