我正在尝试将 3 个 TextBox 控件的值添加到列表中,问题是这些控件是通过单击按钮以编程方式添加的。我不知道如何将 3 个文本框组合在一起,以便将它们的值添加到列表中。
这是一些代码:
按钮点击添加控件:
protected void Button_Add_Click(object sender, EventArgs e)
{
int count = 0;
if (ViewState["count"] != null)
{
count = (int)ViewState["count"];
}
count = PlaceHolder_ForEntries.Controls.Count + 1;
ViewState["count"] = count;
createcontrols();
}
添加控件的方法
protected void createcontrols()
{
int count = 0;
if (ViewState["count"] != null)
{
count = (int)ViewState["count"];
}
while (PlaceHolder_ForEntries.Controls.Count < count)
{
TextBox TextBox_Name = new TextBox();
TextBox TextBox_MemberNo = new TextBox();
TextBox TextBox_Points = new TextBox();
TextBox_Name.Attributes.Add("placeholder", "Navn");
TextBox_Name.ID = "TextBox_Name" + PlaceHolder_ForEntries.Controls.Count.ToString();
TextBox_Name.CssClass = "input-small";
TextBox_MemberNo.Attributes.Add("placeholder", "Medlemsnr.");
TextBox_MemberNo.ID = "TextBox_MemberNo" + PlaceHolder_ForEntries.Controls.Count.ToString();
TextBox_MemberNo.CssClass = "input-small";
TextBox_Points.Attributes.Add("placeholder", "Point");
TextBox_Points.ID = "TextBox_Points" + PlaceHolder_ForEntries.Controls.Count.ToString();
TextBox_Points.CssClass = "input-small";
PlaceHolder_ForEntries.Controls.Add(TextBox_Name);
PlaceHolder_ForEntries.Controls.Add(TextBox_MemberNo);
PlaceHolder_ForEntries.Controls.Add(TextBox_Points);
PlaceHolder_ForEntries.Controls.Add(new LiteralControl("<br />"));
}
}
最后,在保存按钮上运行的代码单击,将项目添加到列表中:
public struct content
{
public string name;
public string memberNo;
public int points;
}
List<content> rows = new List<content>();
protected void LinkButton_Submit_Attendees_Click(object sender, EventArgs e)
{
foreach (Control item in PlaceHolder_ForEntries.Controls)
{
if (item is TextBox)
{
string txt = item.ID.ToString(); // String to run RegEx on
string re1 = ".*?"; // Non-greedy match on filler
string re2 = "(\\d+)"; // Integer Number 1
Regex r = new Regex(re1 + re2, RegexOptions.IgnoreCase | RegexOptions.Singleline);
Match m = r.Match(txt);
int id = Convert.ToInt32(m.Groups[1].ToString());
TextBox txtBox = (TextBox)item;
content row = new content();
if(item.ID.Contains(id.ToString()) && item.ID.Contains("Name"))
{
row.name = txtBox.Text;
}
else if (item.ID.Contains(id.ToString()) && item.ID.Contains("MemberNo"))
{
row.memberNo = txtBox.Text;
}
else if (item.ID.Contains(id.ToString()) && item.ID.Contains("Points"))
{
row.points = Convert.ToInt32(txtBox.Text);
}
rows.Add(row);
}
}
}
我需要的是,对于这个迭代的每三个控件,都使用它们各自的值rows.Add(row)
调用。row.name, row.memberNo and row.points