簡體   English   中英

保存動態創建的文本框的值

[英]Save Values of Dynamically created TextBoxes

伙計們,我每次單擊按鈕都會創建動態TextBoxes。 但是一旦我有想要的文本框那么多..我想保存這些值數據庫表..請指導如何將其保存到數據庫中

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

您必須最遲在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;
        // ...
    }
}

快速而骯臟的方法是僅迭代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...
        }
    }
}

要獲取回發時動態創建的控件的值,您需要在Page_Init事件上重新創建這些控件,然后將加載這些控件的視圖狀態,並獲取控件及其值。

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

希望這可以解決您的問題。快樂編碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM