[ASP.NET]利用DataTable对DropDownList进行数据绑定

ASP.NET控件第一篇---DropDownlist

方法详见下方

        public void LoadDropDownList()
        {
            try
            {
                //获取list
                List list = new List();
                list = ...;
                //创建DataTable
                DataTable dt = new DataTable();
                dt.Columns.Add("ID");
                dt.Columns.Add("Name");
                foreach (var model in list)
                {
                    DataRow dr = dt.NewRow();
                    dr["ID"] = model.ID;
                    dr["Name"] = model.Name;
                    dt.Rows.Add(dr);
                }
                //绑定数据
                DropDownList.DataSource = dt;//指定数据源
                DropDownList.DataValueField = "ID";//DropDownList选项的值
                DropDownList.DataTextField = "Name";//DropDownList显示的文本
                ddCenter.DataBind();//绑定数据
            }
            catch (Exception ex)
            {
              throw ex;
            }


        }


同时DropDownList也可以用下面的方法生成选项


        private void LoadDropDownList()
        {
            try
            {
                List list = new List();
                //获取list
                list = ...;
                foreach (var model in list)
                {
                    DropDownList.Items.Add(new ListItem(model.Name, model.ID);//new ListItem(string text,string value)

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }




你可能感兴趣的:(ASP控件的使用)