【问题标题】:How to bind a custom Enum description to a DataGrid如何将自定义枚举描述绑定到 DataGrid
【发布时间】:2010-10-09 14:05:43
【问题描述】:

问题:我有一个枚举类型,它具有以下样式的描述标签: [URL="http://xml.indelv.com/data-binding-enum.html"]description tag tutorial[/URL] 。我有一个 Windows SQL Server 数据库,我从中提取数据(作为整数然后 castine 到枚举),然后将其绑定到数据网格。我不想在枚举类型中拉出和封装枚举类型,而是想在枚举类型中显示与其关联的描述标签。

这是 ASP -

<asp:GridView ID="StatementGrid" runat="server" AutoGenerateColumns="false" DataKeyNames="statementID" OnRowDeleting="StatementGrid_onDeleting" AllowSorting="False">
                <Columns>
                    <asp:BoundField HeaderText="Type" SortExpression="type" DataField="TypeOfStatement" />
                    <asp:HyperLinkField HeaderText="Statement" DataTextField="StatementText" DataNavigateUrlFormatString="~/Gateway/Statements/View.aspx?statementID={0}" SortExpression="statement" DataNavigateUrlFields="statementID" />
                    <asp:HyperLinkField DataNavigateUrlFields="statementID" DataNavigateUrlFormatString="~/Gateway/Statements/Update.aspx?statementID={0}" NavigateUrl="~/Gateway/Statements/Update.aspx" HeaderText="Edit" Text="<img src='../../Images/News/news_edit.gif' alt='Edit Statement'/>" />
                    <asp:TemplateField HeaderText="Delete">
                        <ItemTemplate>
                            <asp:ImageButton AlternateText="Delete Statement" ID="DeleteButton" ImageUrl="~/Images/News/news_delete.gif" runat="server" CommandName="Delete" OnClientClick="javascript:return confirm('Are you sure you want to delete this statement?');" />
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
                <EmptyDataTemplate>
                    There are no statements to display.
                </EmptyDataTemplate>
            </asp:GridView>

这是绑定的代码 -

[代码]

private void BindData()
        {
            IStatementDao statementDao = DaoFactory.GetStatementDao();
            List<Statement> statements;

            if (Page.Request.RawUrl.Contains("Gateway"))
            {
                statements = statementDao.GetAll();

                StatementGrid.HeaderStyle.CssClass = "GatewayGridHeader";
                StatementGrid.AlternatingRowStyle.CssClass = "GatewayGridAlternatingRow";

            }
            else
            {
                // This should never be reached but it keeps the compiler happy!!
                statements = statementDao.GetAll();
            }

            StatementGrid.DataSource = statements;
            StatementGrid.DataBind();
            DisplayTypeDescriptors();
        }

[/代码]

这里是枚举类-

[代码]

public enum TypeOfStatement 
        { 
            [EnumDescription("Dress Code")] DressCode = 1,
            [EnumDescription("Lunch Time")] LunchTime = 2,
            [EnumDescription("Footwarez")] Footware = 3,
            [EnumDescription("achtung")] Warning = 4,
            [EnumDescription("Banarna")] Banana = 5,
            [EnumDescription("Apfel")] Apple = 6
        };c#

[/代码]

很明显,可以编写一个广泛的方法来做我想做的事,但是有没有更简洁的方法?

【问题讨论】:

    标签: c# asp.net datagrid enums


    【解决方案1】:

    即时将它们包装起来,并巧妙地改变您对 SelectedItem(或您正在使用的任何东西)的处理
    我的示例使用了已经存在的 Description 属性。

    public class DescriptiveEnum<T> where T: struct
    {
        private static readonly Dictionary<T,string> descriptions 
            = new Dictionary<T,string>();
    
        static DescriptiveEnum()
        {
            foreach (FieldInfo field in
                typeof(T).GetFields(BindingFlags.Static 
                | BindingFlags.GetField | BindingFlags.Public))
            {
            descriptions.Add((T)field.GetRawConstantValue(),
                LookupName(field));         
            }
        }
    
        public readonly T Value;
    
        public DescriptiveEnum(T value)
        {
            this.Value = value;     
        }
    
        public override string ToString()
        {
            string s;
            if (!descriptions.TryGetValue(this.Value, out s))
            {           
            // fall back for non declared fields
            s = this.Value.ToString();  
            descriptions[this.Value] = s;
            }
            return s;
        }
    
        private static string LookupName(FieldInfo field)        
        {
            object[] all = field.GetCustomAttributes(
                 typeof(DescriptionAttribute), false);
            if (all.Length == 0)
                return field.Name; // fall back
            else
                return ((DescriptionAttribute)all[0])
                    .Description; // only one needed
        }   
    
        public static BindingList<DescriptiveEnum<T>> Make(
            IEnumerable<T> source)
        {
            var list = new BindingList<DescriptiveEnum<T>>();
            foreach (var x in source)
            list.Add(new DescriptiveEnum<T>(x));
            return list;
        }
    }
    

    示例用法:

    public enum Foo
    {
        [Description("flibble")]
        Bar,
        [Description("wobble")]
        Baz,
        // none present, will use the name
        Bat
    
    }
    
    Form f = new Form();
    f.Controls.Add(new ListBox() 
    {
        Dock = DockStyle.Fill,
        DataSource = DescriptiveEnum<Foo>.Make(
           new Foo[] { Foo.Bar, Foo.Baz, Foo.Bat }),
    });
    Application.Run(f);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-02
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2015-03-29
      • 1970-01-01
      相关资源
      最近更新 更多