在cs文件中如何向下拉列表中添加项目

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个回答

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

希望这可以帮到你。


DropDownList1.Items.Add(new ListItem("所有记录")); 我正在使用这个。在下拉列表中显示所有记录后,无论我从数据库中获取的剩余值是什么,例如名字,当我单击它时,它也必须显示在下拉列表中。 - Venkatesh Chittepu
首先,像你现在所做的那样将下拉列表与数据库值绑定,然后使用适合你的添加或插入方法。 - Manish Parakhiya

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

我建议您还应该将值绑定到下拉列表中。 可以像这样进行操作 -
DropDownList1.DataValueField = "FirstName";

3

在指定的索引位置插入一个项目

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

0

首先在dropdownlist声明的aspx文件中编写onLoad和"addItems"函数,例如:

然后在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);
}       

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接