开发者

combobox selected value in c#

开发者 https://www.devze.com 2023-02-11 10:18 出处:网络
I am working on C#.net windows application. i am filling combobox on my winform by using follows. cmbEMPType.DataSource = objEntityManager.EmployeeTypes();

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开发者_StackOverflow中文版;
}

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


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;


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号