Array of textbox and labels how to get value in submit method in c#
我曾经在下拉列表中动态创建标签和文本框,选择索引更改方法,以及如何在提交方法中获取这些文本框值…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | public partial class StudentMarklistEntry : System.Web.UI.Page { private Label[] sublabels = new Label[7]; private TextBox[] subtextbox = new TextBox[7]; protected void semDropDownList_SelectedIndexChanged(object sender, EventArgs e) { int sem = int.Parse(semDropDownList.SelectedItem.Text); string dept = DeptDropDownList.SelectedItem.Text; if (sem != null) { SqlDataReader subject = Mlist.GetSubjects(d_id,sem); int i = 0; while (subject.Read()) { sublabels[i] = new Label(); subtextbox[i] = new TextBox(); sublabels[i].Text = sub; sublabels[i].ID = (subject["SUB_ID"]).ToString(); markz[i] = Convert.ToString(subject["SUB_ID"]); subtextbox[i].ID ="subtextbox"+i.ToString(); labelPlaceHolder.Controls.Add(sublabels[i]); labelPlaceHolder.Controls.Add(new LiteralControl("")); Textboxholder.Controls.Add(subtextbox[i]); Textboxholder.Controls.Add(new LiteralControl("")); i++; } subject.Close(); } protected void SaveButton_Click(object sender, EventArgs e) { } } |
可以通过两种方式访问控制值
循环通过占位符控件
1 2 3 4 5 6 7 8 9 |
使用request.form
1 2 3 4 5 | var keys = Request.Form.AllKeys.Where(formKey => formKey.Contains("subtextbox")); foreach (var formKey in keys) { selectedValues.Add(Request.Form[formKey]); } |
更新
关于控件的"提交时可见性"按钮单击的问题,这是一个问题,因为您正在DropDownList SelectedIndexChanged事件中创建文本框。在按钮单击事件中,占位符将为空,因为根本没有创建控件。作为解决方法,您可以尝试以下方法。
创建如下函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | private void CreateDynamicControls() { int sem = int.Parse(semDropDownList.SelectedItem.Text); string dept = DeptDropDownList.SelectedItem.Text; if (sem != null) { SqlDataReader subject = Mlist.GetSubjects(d_id, sem); int i = 0; while (subject.Read()) { sublabels[i] = new Label(); subtextbox[i] = new TextBox(); sublabels[i].Text = sub; sublabels[i].ID = (subject["SUB_ID"]).ToString(); markz[i] = Convert.ToString(subject["SUB_ID"]); subtextbox[i].ID ="subtextbox" + i.ToString(); labelPlaceHolder.Controls.Add(sublabels[i]); labelPlaceHolder.Controls.Add(new LiteralControl("")); Textboxholder.Controls.Add(subtextbox[i]); Textboxholder.Controls.Add(new LiteralControl("")); i++; } subject.Close(); } } |
调用pageload中的两个函数(out side the!isPostback块)和semDropDownList_SelectedIndexChanged事件。