none
how to show displaymember in combobox but it should save valuemember in database RRS feed

  • Question

  • i have 2 tables in database 1st PartyTypes columns TypeID,TypeName and

    2nd table Parties which has columns PartyID,PartyName,TypeID  . i am trying to show TypeName in combo box in windowsForms Parties using a method but i want to save TypeID in database. But in combobox it shows only TypeId.

    i want to display TypeName but it should save TypeId.how can i do it. my code below

    //////////////////////////////////////////////////////////

     void fillcBoxPartyName() //my method to show values in combo box
            {
                SqlConnection conn = new SqlConnection("Data Source=isolinks;Initial Catalog=WindowsDb;Integrated Security=True");
                conn.Open();

                sda = new SqlDataAdapter("select TypeId from PartyTypes", conn);

                DataTable dt = new DataTable();

                sda.Fill(dt);

                cBoxPType.DataSource = dt;           
                cBoxPType.ValueMember = "TypeID";
                cBoxPType.DisplayMember = "TypeName";
                conn.Close();
            }

    /////////////////////////////////////////

     private void FormPartyList_Load(object sender, EventArgs e)
            {
                fillcBoxPartyName();

    }  // i use method in formload

    //////////////////////////

    Please Help,

    Sunday, February 4, 2018 6:50 AM

All replies

  • The value is the SelectedValue 


    Success Cor

    Sunday, February 4, 2018 8:14 AM
  • Check if this helps:

    sda = new SqlDataAdapter("SELECT TypeID, TypeName FROM PartyTypes ORDER BY TypeName", conn);

    Sunday, February 4, 2018 9:28 AM
  • A light weight solution (using a DataTable is overkill) is shown below.

    Here I want to display contact types, show contact title and have access to it's primary key. 

    This class represents the data to display in the ComboBox, note ToString returns ContactTitle.

    public class ContactType
    {
        public int ContactTypeIdentifier { get; set; }
        public string ContactTitle { get; set; }
        public override string ToString()
        {
            return ContactTitle;
        }
    }
    
    

    To load and display data from a class (the class is shown below). Note I have not set DisplayMember, this is because the ComboBox uses ToString when DisplayMember is not set thus it will display ContactTitle. I don't set ValueMember but instead since we loaded a List<ContactType> know the SelectedItem is a ContactType so we cast to a ContactType to get the primary key.

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Shown += Form1_Shown;
        }
    
        private void Form1_Shown(object sender, EventArgs e)
        {
            var ops = new DataOperations();
            cboContactTypes.DataSource = ops.LoadContactTypes();
        }
    
        private void button1_Click(object sender, EventArgs e)
        {
            int id = ((ContactType)cboContactTypes.SelectedItem).ContactTypeIdentifier;
            MessageBox.Show($"{cboContactTypes.Text} id: {id}");
        }
    }

    We could place data operations in the form but it's better to use a class e.g.

    using System.Collections.Generic;
    using System.Data.SqlClient;
    
    namespace WindowsFormsApp1
    {
        public class DataOperations
        {
            public string Server = "KARENS-PC";
            public string Catalog = "NorthWindAzure";
            private string ConnectionString = "";
            public DataOperations()
            {
                ConnectionString = $"Data Source={Server};" + 
                    $"Initial Catalog={Catalog};Integrated Security=True";
            }
            public List<ContactType> LoadContactTypes()
            {
                var contactList = new List<ContactType>();
    
                using (SqlConnection cn = new SqlConnection() { ConnectionString = ConnectionString })
                {
                    using (SqlCommand cmd = new SqlCommand() { Connection = cn })
                    {
                        cmd.CommandText = "SELECT ContactTypeIdentifier,ContactTitle FROM dbo.ContactType";
                            cn.Open();
                            var reader = cmd.ExecuteReader();
                            while (reader.Read())
                            {
                                contactList.Add(new ContactType()
                                {
                                    ContactTypeIdentifier = reader.GetInt32(0),
                                    ContactTitle = reader.GetString(1)
                                });
                            }
                        }
                    }
    
                return contactList;
            }
        }
    }
    

    In a real application all data operations would be in the above class and would be accessible to any class or form in your project.


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Sunday, February 4, 2018 10:34 AM
    Moderator