6

这是我的下拉 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

4 回答 4

20

尝试这个

 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

希望这可以帮助。

于 2012-07-31T06:56:04.953 回答
3

在指定索引处插入项目

DropDownListID.Items.Insert(0, new ListItem("Default text", "Default value")
于 2012-07-31T07:00:35.160 回答
3
DropDownList1.Items.Insert(0,new ListItem("AllRecords","itsValue_on_dropdownlist")); // use 0 to show "ALLRecords" text on top in dropdownlist

我建议您也应该将值绑定到下拉列表。像这样 -

DropDownList1.DataValueField = "FirstName";
于 2013-10-04T06:08:04.690 回答
0

首先在下拉列表中使用“addItems”函数编写 onLoad 声明标记 .aspx 文件,如下所示:

然后在cs文件中创建“addItems”函数。

<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);
}       
于 2015-05-18T07:01:57.560 回答