保存动态创建的TextBox的值

时间:2013-02-27 12:46:40

标签: c# asp.net

每次点击按钮时,我都会创建动态TextBox。但是,一旦我有尽可能多的文本框..我想保存这些值数据库表..请指导如何将其保存到数据库

public void addmoreCustom_Click(object sender, EventArgs e)
{
    if (ViewState["addmoreEdu"] != null)
    {
        myCount = (int)ViewState["addmoreEdu"];
    }
    myCount++;
    ViewState["addmoreEdu"] = myCount;
    //dynamicTextBoxes = new TextBox[myCount];

    for (int i = 0; i < myCount; i++)
    {
        TextBox txtboxcustom = new TextBox();
        Literal newlit = new Literal();
        newlit.Text = "<br /><br />";
        txtboxcustom.ID = "txtBoxcustom" + i.ToString();
        myPlaceHolder.Controls.Add(txtboxcustom);
        myPlaceHolder.Controls.Add(newlit);
        dynamicTextBoxes = new TextBox[i];
    }
}

3 个答案:

答案 0 :(得分:1)

您最迟必须在Page_Load中重新创建动态控件,否则ViewState未正确加载。但是,您可以在事件处理程序中添加一个新的动态控件(在页面的生命周期中的page_load之后发生)。

所以addmoreCustom_Click对于重新创建所有已创建的控件来说为时已晚,但添加新控件或阅读Text并不是迟到的工具。

所以这样的事情应该有效(未经测试):

public void Page_Load(object sender, EventArgs e)
{
    if (ViewState["addmoreEdu"] != null)
    {
        myCount = (int)ViewState["addmoreEdu"];
    }

    addControls(myCount);
}

public void addmoreCustom_Click(object sender, EventArgs e)
{
    if (ViewState["addmoreEdu"] != null)
    {
        myCount = (int)ViewState["addmoreEdu"];
    }
    myCount++;
    ViewState["addmoreEdu"] = myCount;

    addControls(1);
}

private void addControls(int count)
{
    int txtCount = myPlaceHolder.Controls.OfType<TextBox>().Count();
    for (int i = 0; i < count; i++)
    {
        TextBox txtboxcustom = new TextBox();
        Literal newlit = new Literal();
        newlit.Text = "<br /><br />";
        txtboxcustom.ID = "txtBoxcustom" + txtCount.ToString();
        myPlaceHolder.Controls.Add(txtboxcustom);
        myPlaceHolder.Controls.Add(newlit);
    }
}

只需枚举PlaceHolder - 控件即可找到您的TextBoxes或使用Linq:

private void saveData()
{
    foreach (TextBox txt in myPlaceHolder.Controls.OfType<TextBox>())
    {
        string text = txt.Text;
        // ...
    }
}

答案 1 :(得分:0)

快速而肮脏的方法是迭代Form集合以寻找正确的值:

if (Page.IsPostBack)
{
    string name = "txtBoxcustom";
    foreach (string key in Request.Form.Keys)
    {
        int index = key.IndexOf(name);
        if (index >= 0)
        {
            int num = Int32.Parse(key.Substring(index + name.Length));
            string value = Request.Form[key];
            //store value of txtBoxcustom with that number to database...
        }
    }
}

答案 2 :(得分:0)

要在回发时获取动态创建的控件的值,您需要在Page_Init事件上重新创建这些控件 然后将加载这些控件的视图状态,您将获得控件和值。

public void Page_Init(object sender, EventArgs e)
{
addControls(myCount);
}

我希望这能解决你的问题 快乐的编码