【问题标题】:how to operate Dynamically Creating dropdown Controls in ASP.NET如何在 ASP.NET 中动态创建下拉控件
【发布时间】:2016-05-02 02:39:13
【问题描述】:

我已经动态创建了 5 个下拉列表。它来自 aspx.cs

for (int i = 0; i < 5; i++)
            {
                DropDownList drop = new DropDownList();
                drop.ID = "dropdownlist" + i;
                form1.Controls.Add(drop);
                form1.Controls.Add(new LiteralControl("<br />"));
             }

我已经有另一个下拉代码,例如

if (!this.IsPostBack)
        {
            string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM RejectedProduct"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    DropDownList1.DataSource = cmd.ExecuteReader();
                    DropDownList1.DataTextField = "Name";
                    DropDownList1.DataValueField = "ID";
                    DropDownList1.DataBind();
                    con.Close();
                }
            }
            DropDownList1.Items.Insert(0, new ListItem("Select Item for adding", "0"));}

如何使用此代码动态创建新的 5 个下拉菜单?

【问题讨论】:

  • 在 asp.net 中使用动态控件是一个坏主意,因为控件在每次回发时都会被破坏并且必须重新创建。他们不会保持你投入的价值。这样做是个坏主意。
  • 动态创建控件只需几个步骤;你错过了很多步骤。看this的回答。如果您有具体问题,请回来再问。

标签: c# sql asp.net webforms


【解决方案1】:

请查看 Mysterio11 & Win 的 cmets。

填充数据的基本思路如下。最重要的是它没有优化。在循环中创建命令和连接是个坏主意。

        if (!this.IsPostBack)
        {
            DropDownList DropDownList1;
            for (int i = 0; i < 5; i++)
            {
                DropDownList1 = (DropDownList)FindControl("dropdownlist" + i);
                string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM RejectedProduct"))
                    {
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        con.Open();
                        DropDownList1.DataSource = cmd.ExecuteReader();
                        DropDownList1.DataTextField = "Name";
                        DropDownList1.DataValueField = "ID";
                        DropDownList1.DataBind();
                        con.Close();
                    }
                }
                DropDownList1.Items.Insert(0, new ListItem("Select Item for adding", "0"));
            }
        }

【讨论】:

  • 抛出异常异常详情:System.NullReferenceException:对象引用未设置为对象的实例。
  • @joyoares 对于延迟,我感到非常抱歉。我用来测试的代码附加到这个link 并且它工作正常。请通过它。
猜你喜欢
  • 2017-07-22
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多