1

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

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];
    }
}
4

3 回答 3

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-Controls 即可找到您的TextBoxes或使用 Linq:

private void saveData()
{
    foreach (TextBox txt in myPlaceHolder.Controls.OfType<TextBox>())
    {
        string text = txt.Text;
        // ...
    }
}
于 2013-02-27T12:57:18.650 回答
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...
        }
    }
}
于 2013-02-27T13:14:18.217 回答
0

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

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

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

于 2013-11-17T06:02:51.723 回答