Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
See more:
How do I load data into combobox from database? I want to display the supportID into the combobox in the form. the code I am using is pasted here. I am calling BindData() in the formload. Ia m getting exception as: Cannot bind to the new display member. Parameter name: newDisplayMember. the code I used is:


C#
public void BindData()
              {
            SqlConnection con = new SqlConnection(@"server=RSTT2; database = Project ;  User                Id=sa; Password=PeaTeaCee5#");
            con.Open();
            string strCmd = "select supportID from Support";
            SqlCommand cmd = new SqlCommand(strCmd, con);
            SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
            DataSet ds = new DataSet();
            da.Fill(ds);
            cbSupportID.DataSource = ds;
            //cbSupportID.DisplayMember = "supportID";
            cbSupportID.ValueMember = "supportID";
            cbSupportID.Enabled = true;
            cmd.ExecuteNonQuery();
            con.Close();
           
        }
Posted
Updated 3-Jan-20 19:44pm
v2

There are so many ways to achieve that:

1). Bind your ComboBox.
C#
this.comboBox1.DisplayMember = "FullName";
this.comboBox1.ValueMember = "your field"; //Field in the datatable which you want to be the value of the combobox 
this.comboBox1.DataSource = ds.Tables["tEmployee"];
2). Manually add items to ComboBox
C#
private void ComboBoxTest_Load(object sender, EventArgs e)

        {
            DataTable dt = new DataTable("Terrorists");
            dt.Columns.Add("FirstName");
            dt.Columns.Add("LastName");
            
            dt.Rows.Add("Osama", "Bin Laden");
            dt.Rows.Add("Saddam", "Hoessein");
            dt.Rows.Add("George", "Bush");

            for (int j = 0; j < dt.Rows.Count; j++)

            {
                string text = dt.Rows[j]["FirstName"].ToString() + " " + dt.Rows[j]["LastName"].ToString();
                this.comboBox1.Items.Add(text);
            }
        }
3). Owner draw the comboBox items:
C#
namespace Sample
{
    public partial class ComboBoxTest : Form
    {
        public ComboBoxTest()
        {
            InitializeComponent();
        }

        private void ComboBoxTest_Load(object sender, EventArgs e)
        {
            DataTable dt = new DataTable("Terrorists");
            dt.Columns.Add("FirstName");
            dt.Columns.Add("LastName");
            
            dt.Rows.Add("Osama", "Bin Laden");
            dt.Rows.Add("Saddam", "Hoessein");
            dt.Rows.Add("George", "Bush");

            this.comboBox1.DisplayMember = "FirstName";
            this.comboBox1.DataSource = dt;
            this.comboBox1.DrawMode = DrawMode.OwnerDrawFixed;
            this.comboBox1.DrawItem += new DrawItemEventHandler(comboBox1_DrawItem);
        }
 
        void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            DataRowView dv = this.comboBox1.Items[e.Index] as DataRowView;
            string text = dv["FirstName"].ToString() +" "+ dv["LastName"].ToString();
            e.Graphics.DrawString(text, e.Font, new SolidBrush(e.ForeColor), e.Bounds);
        }
    }
}
Take your pick :)
 
Share this answer
 
v2
its very simple
but , dont forget to add those things

C#
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;





C#
        SqlDataAdapter da;
        DataTable dtbl = new DataTable();

        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["sql"].ToString());
// you should use your Connection String 
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandText = "select ClerkId from Clerk"; // you should use your table name .
        

        try
        {
            da = new SqlDataAdapter(cmd);
            da.Fill(dtbl);
            Combo1.DataSource = dtbl;
            Combo1.DataTextField = dtbl.Columns["ClerkId"].ToString();
            Combo1.DataBind();
        }
        catch (Exception ex)
        {
            con.Close();
         
        }
 
Share this answer
 
v3
C#
public void BindData()
       {
           SqlConnection con = Helper.getconnection();
           con.Open();
           string strCmd = "select supportID, Name from Support";
           SqlCommand cmd = new SqlCommand(strCmd, con);
           SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
           DataSet ds = new DataSet();
           da.Fill(ds);
           cbSupportID.DataSource = ds.Tables[0];
           cbSupportID.DisplayMember = "Name";
           cbSupportID.ValueMember = "supportID";
           cbSupportID.Enabled = true;
           this.cbSupportID.SelectedIndex = -1;
           cmd.ExecuteNonQuery();
           con.Close();
       }
 
Share this answer
 
Here is the sample code to fill data from database into ddlstate dropdown

SqlConnection cn = mcls.OpenCn();
               string sql;
               sql = "Select stateid,statename from StateMaster";
               DataTable dt = new DataTable();
               SqlDataAdapter da = new SqlDataAdapter(sql, cn);
               da.Fill(dt);
               ddlstate.DataSource = dt;
               ddlstate.DataBind();
               ddlstate.DataTextField = "StateName";
               ddlstate.DataValueField = "Stateid";
               ddlstate.DataBind();
               ddlstate.Items.Insert(0, "-Please Select-");
               ddlstate.SelectedIndex = 0;
 
Share this answer
 
Comments
Richard Deeming 12-Jun-17 15:57pm    
This question was asked, answered, and solved FOUR YEARS AGO.

And your solution adds nothing to the existing solutions - apart from the overhead of calling DataBind twice because you didn't bother to understand the code you've posted.
write a method in from.Here BindDepartment is my methodname:

private void BindDepartment()
{
try
{
DataTable dt = new DataTable();
objEmployee = new Employee();
dt=objEmployee.GetDeprtmentofDrop(Convert.ToString(comboBoxdepartment.SelectedValue));
DataRow dr = dt.NewRow();
dr["DeptName"] = 0;
dr["DeptName"] = "--Select Department--";
dt.Rows.InsertAt(dr, 0);
comboBoxdepartment.DataSource = dt;
comboBoxdepartment.DisplayMember = "DeptName";
comboBoxdepartment.ValueMember = "DeptName";
}
catch (Exception ex)
{
throw ex;
}
}
pass parameters to the method

public DataTable GetDeprtmentofDrop(string DeptName)
{
if (Connection == null)
{
Connection = new SqlConnection();
}
SqlCommand cmd = Connection.CreateCommand();
cmd.CommandText = "spDepartment";
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.Parameters.AddWithValue("@Action", "select");
cmd.Parameters.AddWithValue("@DeptName", DeptName);
DataTable dt = new DataTable();
da.Fill(dt);
return dt;
}


NOTEHere ObjEmployee Is a object of your classname
Ex:- Employee ObjEmployee=new Employee;
 
Share this answer
 
v2

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