using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Mod
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int c = 0;
private void button1_Click(object sender, EventArgs e)
{
TextBox txtRun = new TextBox();
txtRun.Name = "txtDynamic" + c++;
txtRun.Location = new System.Drawing.Point(20, 18 + (20 * c));
txtRun.Size = new System.Drawing.Size(200,15);
this.Controls.Add(txtRun);
}
private void button2_Click(object sender, EventArgs e)
{
List<string>tilelocation = List<string>();
tilelocation.Add(); //What goes in this method's arguments?
}
}
}
这是我的代码。 Button1创建了一个理论上无限的文本框,但我希望将这些动态生成的文本框中的文本添加到列表中。怎么办呢?
[编辑]
如何在消息框中全部显示它们,每个都在不同的行上?
答案 0 :(得分:1)
您需要保留对控件的引用。
另一个秘密是你必须将它保存在ViewState中,以便在回发之间可用。
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
int c = 0;
private List<TextBox _lstTextBoxList;
public List<TextBox> lstTextBoxList {
get {
if(_lstTextBoxList == null) {
_lstTextBoxList = ViewState["lstTextBoxList"] as List<TextBox>;
}
return _lstTextBoxList;
}
set { ViewState["lstTextBoxList"] = _lstTextBoxList = value; }
}
private void button1_Click(object sender, EventArgs e) {
TextBox txtRun = new TextBox();
txtRun.Name = "txtDynamic" + c++;
txtRun.Location = new System.Drawing.Point(20, 18 + (20 * c));
txtRun.Size = new System.Drawing.Size(200,15);
this.Controls.Add(txtRun);
lstTextBoxList.Add(txtRun);
}
private void button2_Click(object sender, EventArgs e) {
// Not sure of your goal here:
List<string> tilelocation = List<string>();
tilelocation.Add(lstTextBoxList[lstTextBoxList.Count - 1]);
// I would assume you wanted this:
List<string> strValues = lstTextBoxList.Select<TextBox,string>(t => t.Text).ToList();
}
}
答案 1 :(得分:0)
但我想在这些动态生成的文本框中添加文本 一个列表。怎么办呢?
您应该使用new List<string>
之类的:
private void button2_Click(object sender, EventArgs e)
{
List<string> tilelocation = new List<string>();
foreach(TextBox tb in this.Controls.OfType<TextBox>().Where(r=> r.Name.StartsWith("txtDynamic"))
titlelocation.Add(tb.Text);
//if you want a string out of it.
string str = string.Join(",", titlelocation);
MessageBox.Show(str);
}
编辑:对于新行使用的每个文本:
string str = string.Join(Environment.NewLine, titlelocation);
MessageBox.Show(str);
答案 2 :(得分:0)
我不知道您为什么要使用单独的button2单击事件来添加文本。为什么不使用全局变量tilelocation,并在button1_click事件中将文本添加到此列表?类似的东西:
txtRun.Text=Your Text;
tilelocation.add(Your Text);
如果要在消息框中显示它们,请添加代码:
string str="";
foreach(text in tilelocation)
{
str+=text;
}
MessageBox.Show(str);