I saw many many articles on this but none helped so far. My ComboBox name is cbPlan. I want to Retrieve PlanName in it's display but want to actually hold it PlanID. Following code displays both Names and IDs. I tried ValueMember, DisplayMember, properties but couldn't get it sorted yet. Finally, even if this works out, how will I get to insert PlanID in another table? Will i use Convert.ToString(cbPlan.Text) - which would bring the PlanName and not the ID. Please help on this - A big thank you in advance! :) P.S. PlanID's data type is int.
private void cbPlan_Click(object sender, EventArgs e)
{
cbPlan.Items.Clear();
string pullsub = "select PlanID,PlanName from fbkPlanMaster(nolock)";
string connString = ConfigurationManager.ConnectionStrings["Dbconn"].ToString();
SqlConnection connection = new SqlConnection(connString); // defining sql connection
SqlCommand cmd = new SqlCommand(pullsub, connection);
cmd.CommandText = pullsub;
connection.Open();
SqlDataReader drd = cmd.ExecuteReader();
while (drd.Read())
{
cbPlan.Items.Add(drd["PlanID"]);
cbPlan.Items.Add(drd["PlanName"]);
cbPlan.ValueMember = "PlanID";
cbPlan.DisplayMember = "PlanName";
}
}
First of all modifying your approach to add items to your combo-box you should not use Reader. Second, why are you adding PlanID if you don't want to display it? This code may help you ...
cbPlan.DataSource = dt;
cbPlan.ValueMember = "PlanID";
cbPlan.DisplayMember = "PlanName";
You should first get your data from database into some datatable or a dataset as above cbPlan.DataSource = dt;
This will hold your id as ValueMember as an ID and its displayed text will be PlanName. Hope this helps you.