【问题标题】:dropdownlist in c#C#中的下拉列表
【发布时间】:2010-11-22 10:30:02
【问题描述】:

我想在表单加载时在下拉列表中显示一个数据库字段。谁能告诉我怎么做。

请帮忙

【问题讨论】:

    标签: c# asp.net mysql


    【解决方案1】:

    一如既往地从定义你的模型开始:

    public class Item
    {
        public string Id { get; set; }
        public string Label { get; set; }
    }
    

    然后你的存储库:

    public interface IRepository
    {
        IEnumerable<Item> GetItems();
    }
    

    然后实现这个仓库:

    public class MySQLRepository: IRepository
    {
        public IEnumerable<Item> GetItems()
        {
            using (var conn = new MySqlConnection("SOME CONNECTION STRING"))
            using (var cmd = conn.CreateCommand())
            {
                conn.Open(); 
                cmd.CommandText = "SELECT id, name FROM items;";
                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        yield return new Item
                        {
                            Id = reader.GetString(0),
                            Label = reader.GetString(1),
                        };
                    }
                }
            }
        }
    }
    

    最后在表单中使用此存储库的实例来获取数据:

    myDDL.DataSource = repository.GetItems();
    myDDL.DataValueField = "Id";
    myDDL.DataTextField = "Label";
    myDDL.DataBind();
    

    【讨论】:

      【解决方案2】:

      关于你的问题

      1- 获取数据表中的数据。

      2- 将列表的 DataSource 属性设置为步骤 1 中的数据表

      3- 设置DataTextField,DataValueField

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多