向DropDownList 下拉框添加新选项

     大家有没有遇见过这样的情况,假如有一个下拉框,现在让你在下拉框里面添加一个新的选项如“请选择”,而数据库里面又不存在这一选项》要怎么做,下面为大家推荐两种写法:

数据库的表为类别表:

create table LE_FoodType
(
FoodTypeID int primary key identity(1,1),
FoodTypeName nvarchar(50) not null
)
go
insert into LE_FoodType values('主食')
insert into LE_FoodType values('热菜系列')
insert into LE_FoodType values('经典凉拌')
insert into LE_FoodType values('海鲜盛宴')

第一种:

          Database db = DatabaseFactory.CreateDatabase("constr");

            string sql = string.Format("select * from LE_FoodType");
            DataSet ds = db.ExecuteDataSet(CommandType.Text,sql);
            DropDownList1.DataSource = ds.Tables[0];
            DropDownList1.DataValueField = "FoodTypeID";
            DropDownList1.DataTextField = "FoodTypeName";

            DropDownList1.DataBind();

          现在绑出的效果如下

现在在绑定后添加代码如下:

            DropDownList1.DataBind();
            ListItem item = new ListItem();
            item.Text = "查询全部";

            DropDownList1.Items.Insert(0,item);

其中0带表你要添加的那项的Id值。效果如下:

上面的几行代码可以替换成一句代码:  DropDownList1.Items.Insert(0,new ListItem("全部类别"));

有细心的人会发现,为什么我使用  DropDownList1.SelectedItem.Value 获取“查询全部”不是编号0而是一个文本值‘查询全部’? 我们在ListItem()里面打个逗号会发现里面是俩个值,而我们只写一个正确写法为:

DropDownList1.Items.Insert(0,new ListItem("全部类别","0"));

第二种方法:

        string sql = string.Format("select * from LE_FoodType");
            DataSet ds = db.ExecuteDataSet(CommandType.Text,sql);
            DataRow row = ds.Tables[0].NewRow();//创建新行
            //根据数据库字段进行赋值
            row["FoodTypeID"] = "0";
            row["FoodTypeName"] = "查询全部";
            //把创建的新行插入到新的表格里面。
            ds.Tables[0].Rows.InsertAt(row,0);
            DropDownList1.DataSource = ds.Tables[0];
            DropDownList1.DataValueField = "FoodTypeID";
            DropDownList1.DataTextField = "FoodTypeName";

            DropDownList1.DataBind();

注意:你创建的新行要放在数据源绑定之前,要不然你创建的新行会不显示的。

上面的代码实现效果与第一种实现的效果是一样的。

我上面使用的数据访问是使用微软企业库进行操作的。

我知道的方法就这些,不知道大家有没有什么好的方法,大家可以一起讨论讨论,上面有什么说错的可以指出来,虚心求教。


猜你喜欢

转载自blog.csdn.net/gods_boy/article/details/80226226