combobox选择值在c#

combobox选择值在c#

本文介绍了combobox选择值在c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在C#.net Windows应用程序。我使用以下方式在我的winform上填充combobox。

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";

其中 objEntityManager.EmployeeTypes(); 将List从Linq获取到sql服务器的manager方法。这是工作正常。

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

但是当我选择项目形式组合框,并点击按钮,然后在按钮点击事件我得到 cmbEMPType.SelectedValue as EmpType 返回类型而不是其ID。为什么要这样?我不想再创建一个EmpType对象。需要简单选择的值。也不能保持对SelectedIndex的信心。

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;
}

但是要求创建EMPType对象。

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

推荐答案

问题是你的代码的顺序。请删除第一行代码到最后一行。您将从 cmbEMPType.SelectedValue 中获取一个int值( iEMPTypeId )。

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

这篇关于combobox选择值在c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 18:45