ASP.NET 2.0中给DropDownList服务器控件添加项的新方法

ASP.NET 2.0中,可以在数据绑定时,通过设置DropDownListAppendDataBoundItems属性为true,在数据绑定之前添加一个新的项目,并且这个新加的项目会保存在ViewState之中。下面就是一个实现的例子:

C#代码

<%@ Page Language="C#" %>

<%@ Import Namespace="System.Data" %>

 

 

<!DOCTYPE html PUBLIC "-//W 3C //DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<script runat="server">

    ICollection CreateDataSource()

    {

        DataTable dt = new DataTable();

        DataRow dr;

        dt.Columns.Add(new DataColumn("id", typeof(Int32)));

        dt.Columns.Add(new DataColumn("text", typeof(string)));

        for (int i = 0; i < 6; i++)

        {

            dr = dt.NewRow();

            dr[0] = i;

            dr[1] = "列表项目 " + i.ToString();

            dt.Rows.Add(dr);

        }

        DataView dv = new DataView(dt);

        return dv;

    }

 

    protected void Button1_Click(object sender, EventArgs e)

    {

        Response.Write("<li>DropDownList1 您选择的项目:" + DropDownList1.SelectedValue

      + " ; " + DropDownList1.SelectedItem.Text);

        Response.Write("<li>DropDownList2 您选择的项目:" + DropDownList2.SelectedValue

          + " ; " + DropDownList2.SelectedItem.Text);

 

    }

   

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            DropDownList1.AppendDataBoundItems = true;

            DropDownList1.Items.Add(new ListItem("-- 请选择一个选择项 --", ""));

            DropDownList2.DataSource = DropDownList1.DataSource = CreateDataSource();

            DropDownList2.DataTextField = DropDownList1.DataTextField = "text";

            DropDownList2.DataValueField = DropDownList1.DataValueField = "id";

            DropDownList1.DataBind();

            DropDownList2.DataBind();

        }

    }

 

</script>

 

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

    <title>DropDownList 补充例子</title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:DropDownList ID="DropDownList1" runat="server">

  </asp:DropDownList>

  <asp:DropDownList ID="DropDownList2" runat="server" AppendDataBoundItems="true">

  <asp:ListItem Text="请选择" Value=""></asp:ListItem>

  </asp:DropDownList>

  <asp:Button ID="Button1" runat="server" Text="得到选择的值" OnClick="Button1_Click" />

    </div>

    </form>

</body>

</html>

 

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值