繁体   English   中英

将组合框绑定到枚举并将值传递回存储过程

[英]Binding a combobox to an enum and passing the values back to a stored procedure

您好,我是 C# 新手,如果我试图以完全错误的方式执行此操作,我深表歉意!

我正在尝试使用枚举中的值填充组合框,然后将枚举中的值传递回存储过程。

至于在组合框中显示正确的项目,它工作正常我在下拉菜单中得到“订单号”和“帐号”我试图让用户可以选择其中一个选项,我可以将 1 或 2 传回我的存储过程。

所有与组合框相关的代码都来自我在尝试自己解决这个问题时在这里找到的其他帖子。

目前我正在使用 -

public enum SearchType
        {
            [Description("Order Number")]
            OrderNumber = 1,
            [Description("Account Number")]
            AccountNumber = 2
        }

public void LoadComboBoxSearchType(ComboBox cbo)
        {
            cbo.DataSource = System.Enum.GetValues(typeof(Customers.SearchType))
            .Cast<System.Enum>()
            .Select(value => new
            {
                (Attribute.GetCustomAttribute(value.GetType().GetField(value.ToString()), typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
                value
            })
            .OrderBy(item => item.value)
            .ToList();

            cbo.DisplayMember = "Description";
            cbo.ValueMember = "value";
        }

因此,当我尝试将值从组合框(期望 1 或 2)传递到存储过程时,我只是获得了“值”。

我正在调用存储过程,例如 -

    private void ButtonOutboundGridView_Click(object sender, EventArgs e)
    {
        OutboundDatas = DataAccess.GetOutboundDatas(ComboBoxSearchType.ValueMember, TextBoxSearchRef.Text);
    }

这是使用枚举的糟糕方式吗,我是否过于复杂了?

谢谢!

我设法找到了解决方案......我想我会把它发布给任何可能看到类似问题的人 -

我结合了此链接中的代码-

如何将枚举绑定到组合框

使用我已经拥有的内容,在组合框中显示描述(因此可以使用文本值更好地格式化),但也将值保留为枚举中的数值。

public void LoadComboBoxSearchType(ComboBox cbo)
        {
            cbo.DataSource = System.Enum.GetValues(typeof(Customers.SearchType))
           .Cast<Customers.SearchType>()
           .Select(p => new
           {
               Key = (int)p,
               Value = (Attribute.GetCustomAttribute(p.GetType().GetField(p.ToString()),
                       typeof(DescriptionAttribute)) as DescriptionAttribute).Description,
               p
           })
           .ToList();

            cbo.DisplayMember = "Value";
            cbo.ValueMember = "Key";
        }

所以现在我可以在我的组合框上使用 .SelectedValue 将键(1 或 2)传递给我的存储过程。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM