如何在cs文件的Dropdown列表中添加Item

时间:2012-07-31 06:52:53

标签: c# asp.net sql-server-2008

这是我的CS下拉文件:

protected void BindDropDownList()     

    {

        DataTable dt = new DataTable();
        string connString = System.Configuration.ConfigurationManager.AppSettings["EyeProject"];
        SqlConnection conn = new SqlConnection(connString);


        try
        {
            conn.Open();
            string sqlStatement = "SELECT FirstName FROM tbl_UserDetails";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, conn);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                DropDownList1.DataSource =dt;


                DropDownList1.DataTextField = "FirstName"; // the items to be displayed in the list items

                DropDownList1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "No Data Found To display in the DropDown List";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }


    }



By using this one iam getting values of table Firstname values now i want to add one more item Called ALLrecords. 

How can i add it.

this is my Aspx file 

 <div class="label">
                                    Select Name:
                                    <asp:DropDownList ID="DropDownList1" runat="server">

                                    </asp:DropDownList>
                                </div>

4 个答案:

答案 0 :(得分:18)

试试这个

 DropDownList1.Items.Add(new ListItem("All Record"));

如果您想添加值为

的项目
 DropDownList1.Items.Add(new ListItem("All Record","0"));

 //or if you want to add at particular index then

 DropDownList1.Items.Insert(0,new ListItem("All Record"));// 0 is index of item
希望这会有所帮助。

答案 1 :(得分:3)

在指定的索引处插入项目

DropDownListID.Items.Insert(0, new ListItem("Default text", "Default value")

答案 2 :(得分:3)

DropDownList1.Items.Insert(0,new ListItem("AllRecords","itsValue_on_dropdownlist")); // use 0 to show "ALLRecords" text on top in dropdownlist

我建议你也应该将值绑定到dropdownlist。 像这样 -

DropDownList1.DataValueField = "FirstName";

答案 3 :(得分:0)

首先使用&#34; addItems&#34;写onLoad;函数在dropdownlist中声明标记.aspx文件,如下所示:

然后创建&#34; addItems&#34;功能在cs文件中。

<asp:DropDownList ID="DropDownList1" runat="server" OnLoad="addDeleteItems" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

protected void addItems(object sender, System.EventArgs e)
{
     DropDownList ddl = (DropDownList)sender;           
     ListItem newItem = new ListItem("rose", "i");
     ddl.Items.Add(newItem);
}