gpt4 book ai didi

c# - 从动态文本框中获取用户输入

转载 作者:行者123 更新时间:2023-11-30 12:29:41 27 4
gpt4 key购买 nike

我有两个按钮。一个用于创建 Textbox 的按钮,另一个用于提交信息。创建 textbox 后,我无法检索用户文本。这是代码:

 private void CreateTextBox(int j) //Creates the fields / cells
{


TextBox t = new TextBox();
t.ID = "Textbox" + j;
//t.Text = "Textbox" + j;
lstTextBox.Add(t);
var c = new TableCell();
c.Controls.Add(t);
r.Cells.Add(c);
table1.Rows.Add(r);
Session["test"] = lstTextBox;

}
protected void Button2_Click(object sender, EventArgs e)
{
string[] holder = new string[4];
for (int i = 0; i < holder.Length; i++)
{
holder[i] = "";
}
List<TextBox> lstTextBox = (Session["test"] as List<TextBox>);
if (lstTextBox.Count < Counter)
{
int i = lstTextBox.Count;
for (int j = 0; j < i; j++)
{

holder[j] = lstTextBox[j].Text;

}
SqlConnection conns = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDBConnectionString1"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into LoanerForm (field0, field1, field2, field3) Values (@field0, @field1, @field2, @field3)", conns);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@field0", holder[0]);
cmd.Parameters.AddWithValue("@field1", holder[1]);
cmd.Parameters.AddWithValue("@field2", holder[2]);
cmd.Parameters.AddWithValue("@field3", holder[3]);
conns.Open();
cmd.ExecuteNonQuery();
conns.Close();

}

Counter = 0;

Button1.Visible = true; //Going to submit data to SQL

}

提前致谢!

最佳答案

这是动态创建文本框的方法。它跟踪 ViewState 中文本框的数量。

<asp:Button runat="server" ID="Button1" OnClick="Button1_Click" 
Text="Create TextBoxes" />
<asp:Button runat="server" ID="Button2" OnClick="Button2_Click"
Text="Save TextBoxes to Database" />
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>

public int Counter
{
get { return Convert.ToInt32(ViewState["Counter"] ?? "0"); }
set { ViewState["Counter"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
// Need to reload those textboxes on page back
// Otherwise, they will becomes null
int total = Counter;
for (int i = 0; i < total; i++)
{
var textBox = new TextBox
{
ID = "TextBox" + i,
Text = "TextBox" + i
};
PlaceHolder1.Controls.Add(textBox);
}
}

private void CreateTextBox(int id)
{
var textBox = new TextBox
{
ID = "TextBox" + id,
Text = "TextBox" + id
};
PlaceHolder1.Controls.Add(textBox);
}

protected void Button1_Click(object sender, EventArgs e)
{
CreateTextBox(Counter);
Counter = Counter + 1;
}

protected void Button2_Click(object sender, EventArgs e)
{
int total = Counter;
for (int i = 0; i < total; i++)
{
var textbox = PlaceHolder1.FindControl("TextBox" + i) as TextBox;
var text = textbox.Text;
// Do something with text
}
}

关于c# - 从动态文本框中获取用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18153470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com