combobox selected value in c#

半城伤御伤魂 提交于 2019-12-11 00:26:37

问题


I am working on C#.net windows application. i am filling combobox on my winform by using follows.

cmbEMPType.DataSource = objEntityManager.EmployeeTypes();
cmbEMPType.DisplayMember = "EMPTypeName";
cmbEMPType.ValueMember = "EMPTypeId";

where objEntityManager.EmployeeTypes(); in the manager method that gets the List from Linq to sql server. this is working fine.

but as i select the item form combo box, and clicked the button then in the button click event i am getting cmbEMPType.SelectedValue as EmpType return type rather than its Id. why should this? I don't want to create one more EmpType object. need simple selected value. also can not keep faith with SelectedIndex. it may varies for item each time.

**Edited**
      public List<EMPType> EmployeeTypes()
        {
            List<EMPType> EMPTypeList = null;
            try
            {
                if (CommonDataObject.dataContext.EMPAllTypes.Any())
                {
                    EMPTypeList = CommonDataObject.dataContext.EMPAllTypes.ToList();
                }
                return EMPTypeList;
            }
            catch
            {

                return EMPTypeList;
            }

        }

Edited

   private void btnSave_Click(object sender, EventArgs e)
        {

iEMPTypeId = cmbEMPType.SelectedValue;
}

here I must get inte. but asking of create the EMPType object.


回答1:


This is the correct and expected behavior, you can't change it.

SelectedValue should return the type of the property, e.g. if EMPTypeId is integer it should return integer - please post more code so that we can try figuring out why you get different return value.

If by any chance you're using SelectedItem then have such code to get the ID:

 int selectedID = (cmbEMPType.SelectedItem as EmpType).EMPTypeId;

To handle cases when there's nothing selected:

object oSelectedEmp = cmbEMPType.SelectedItem;
int selectedID = oSelectedEmp == null ? -1 : (oSelectedEmp as EmpType).EMPTypeId;



回答2:


The problem is the sequence of your code. Please remove the first line code to the last line. You will get an int value (iEMPTypeId) from cmbEMPType.SelectedValue.

cmbEMPType.DisplayMember = "EMPTypeName"; 
cmbEMPType.ValueMember = "EMPTypeId"; 
cmbEMPType.DataSource = objEntityManager.EmployeeTypes();

iEMPTypeId = cmbEMPType.SelectedValue



回答3:


Another option is to override the toString function in your EMPType class. As Edwin de Koning stated "If no ValueMember is specified it gives a ToString() representation."

Something like (I cant test it at the moment):

public override string ToString()
{
    return this.ID;
}

You can check out this article: http://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx



来源:https://stackoverflow.com/questions/4992129/combobox-selected-value-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!