c# - 如何在cs文件的下拉列表中添加项目

标签 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>

最佳答案

试试这个

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

如果你想添加有值(value)的项目

 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

希望对您有所帮助。

关于c# - 如何在cs文件的下拉列表中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11734683/

相关文章:

sql-server - SQL Server 数据库文件未被截断

sql - SQL Use DatabaseName to NOT USE database 的反义词是什么?

c# - 使用 C# 在 LAN 上唤醒

c# - 在列表中存储不同的类型?

javascript - 为什么 ASP.NET 隐藏字段变得可见

c# - 解密 HTTPS 实例上生成的 WebResource.axd URL

c# - 用我自己的替换父类事件

c# - 无法识别的元素 unitTestProvider

ASP.NET - cookieless=UseCookies - 浏览器中只有 session ID?没有客户端cookie?

sql - SQL Server 2008 r2中的XML查询/修改问题