文本框和标签数组如何在c#中提交方法中获取值
本文关键字:提交 方法 获取 标签 数组 文本 | 更新日期: 2023-09-27 18:14:23
我已经使用创建标签和文本框动态在下拉列表中选择索引改变的方法,以及如何在提交方法....中获得这些文本框值
<>之前公共部分类StudentMarklistEntry: System.Web.UI.Page{private Label[] subablabels = new Label[7];private TextBox[] subtextbox = new TextBox[7];semDropDownList_SelectedIndexChanged(对象发送者,EventArgs){int sem = int. parse (semdropdownlist . selecteitem . text);字符串deppt = deptdropdownlist . selecteitem . text;If (sem != null){SqlDataReader subject = Mlist.GetSubjects(d_id,sem);Int I = 0;而(subject.Read ()){subablabels [i] = new Label();subtextbox[i] = new TextBox();sublabels[我]。Text = sub;sublabels[我]。ID = (subject["SUB_ID"]).ToString();markz[i] = Convert.ToString(subject["SUB_ID"]);subtextbox[我]。ID = "subtextbox"+i.ToString();labelPlaceHolder.Controls.Add (sublabels[我]);labelPlaceHolder.Controls。添加(新LiteralControl (" "));Textboxholder.Controls.Add (subtextbox[我]);Textboxholder.Controls。添加(新LiteralControl (" "));我+ +;}subject.Close ();}SaveButton_Click(对象发送者,EventArgs e){}}您可以通过两种方式访问控件值
遍历占位符控件
IList<string> selectedValues= new List<string>();
foreach (Control control in placeHolderText.Controls)
{
if (control is TextBox)
{
var textBox = control as TextBox;
selectedValues.Add(textBox.Text);
}
}
使用request.form var keys = Request.Form.AllKeys.Where(formKey => formKey.Contains("subtextbox"));
foreach (var formKey in keys)
{
selectedValues.Add(Request.Form[formKey]);
}
关于提交按钮单击时控件可见性的问题,这是一个问题,因为您正在创建下拉列表selectedindexchanged事件中的文本框。在单击按钮事件中,占位符将为空,因为根本没有创建控件。作为一种变通方法,您可以尝试以下方法:
创建如下函数
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(在!IsPostBack块之外)和semDropDownList_SelectedIndexChanged事件中的函数。