繁体   English   中英

动态生成文本框 asp.net

[英]Dynamically generating textboxes asp.net

我创建了一个 function 来根据从文本框中选择的数量动态创建文本框,另外我正在使用这些文本框来显示数据库中的数据。 但是,当用户从下拉列表中选择了五个,并且已经存在三个文本框时,它不会再添加 2 个文本框,而是添加额外的 5 个文本框。 为了添加额外的文本框,我做了什么?

 protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
    {
        populate();
    }

  public void populate()
    {

        int count = Convert.ToInt32(TotalSeal.SelectedItem.Value);
        for (int i = 0; i < count; i++)
        {
            if (i < 0)
            {

            }
            else
            {

                TextBox tx = new TextBox();
                tx.MaxLength = 10;
                tx.Width = 100;
                phSealNum.Controls.Add(tx);
                phSealNum.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));

                ControlCache.Add(tx);
            }
        }
    }

更新

  public void populate()
    {
        //ControlCache = new List<Control>();
        //phSealNum.Controls.Clear();

        int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);
        int currentItems = phSealNum.Controls.OfType<TextBox>().Count();
        int totalitems = targetCount - currentItems;
        if (totalitems <= 7)
        {
            for (int i = 0; i < totalitems; i++)
            {

                TextBox tx = new TextBox();
                tx.MaxLength = 10;
                tx.Width = 100;
                phSealNum.Controls.Add(tx);
                phSealNum.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));

                ControlCache.Add(tx);
            }
        }
        else
        {
            lblError.Text = targetCount + " exceeds number of seals";
        }
    }

使用@indrit-kello 逻辑应该是这样的:

protected void TotalSeal_SelectedIndexChanged(object sender, EventArgs e)
    {
        populate();
    }

    public void populate()
    {

        int targetCount = Convert.ToInt32(TotalSeal.SelectedItem.Value);

        if(targetCount > 7)
          targetCount = 7;

        int currentItems = 0;//TODO
        for (int i = currentItems; i < targetCount; i++)
        {
            TextBox tx = new TextBox();
            tx.MaxLength = 10;
            tx.Width = 100;
            phSealNum.Controls.Add(tx);
            phSealNum.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"));

            ControlCache.Add(tx);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM