C# 从文本框到列表视图
我正在开发一个带有多行文本框和C# 从文本框到列表视图,c#,listview,textbox,C#,Listview,Textbox,我正在开发一个带有多行文本框和列表视图的C应用程序 文本框的内容如下所示: John Smith Joe Bronstein Susan Jones Adam Feldman Date Name 6/27/2013 John Smith 6/27/2013 Joe Bronstein 6/27/2013 Susan Jones 6/27/2013 Adam Feldman string[] line = textBox1.Lines; // get all the lin
列表视图的C应用程序
文本框的内容如下所示:
John Smith
Joe Bronstein
Susan Jones
Adam Feldman
Date Name
6/27/2013 John Smith
6/27/2013 Joe Bronstein
6/27/2013 Susan Jones
6/27/2013 Adam Feldman
string[] line = textBox1.Lines; // get all the lines of text from Multiline Textbox
int i = 0; // index for the array above
foreach (ListViewItem itm in listView1.Items) // Iterate on each Item of the ListView
{
itm.SubItems.Add(line[i++]); // Add the line from your textbox to each ListViewItem using the SubItem
}
列表视图有两列:Date
和Name
到目前为止,我可以将当前日期放入listview的date列中。接下来,我需要将名称复制到Name列中。列表视图应如下所示:
John Smith
Joe Bronstein
Susan Jones
Adam Feldman
Date Name
6/27/2013 John Smith
6/27/2013 Joe Bronstein
6/27/2013 Susan Jones
6/27/2013 Adam Feldman
string[] line = textBox1.Lines; // get all the lines of text from Multiline Textbox
int i = 0; // index for the array above
foreach (ListViewItem itm in listView1.Items) // Iterate on each Item of the ListView
{
itm.SubItems.Add(line[i++]); // Add the line from your textbox to each ListViewItem using the SubItem
}
那么如何将textbox
中每一行的名称复制到listview
中每一行的name
列中?这将使用当前日期将所有名称从textbox添加到listview:
var date = DateTime.Now.ToShortDateString();
foreach (var line in textBox.Lines)
listView.Items.Add(new ListViewItem(new string[] { date, line}));
工作原理:我们正在枚举文本框
属性行
,它逐行返回名称。对于新建的每一行ListViewItem
,在ListView
中为每一列创建字符串数组。然后将该项添加到列表视图中。Lazyberezovsky答案非常有效
但是,如果您已经在列表视图中添加了一个项目,并且您想在已经添加了日期之后添加行(老实说,我对此表示怀疑,但这只是一个猜测)。然后需要使用子项
将每一行添加到一个新列中。现在,假设您的列表视图
的项目数与多行
文本框
中的行数
相同
因此,您的代码可能如下所示:
John Smith
Joe Bronstein
Susan Jones
Adam Feldman
Date Name
6/27/2013 John Smith
6/27/2013 Joe Bronstein
6/27/2013 Susan Jones
6/27/2013 Adam Feldman
string[] line = textBox1.Lines; // get all the lines of text from Multiline Textbox
int i = 0; // index for the array above
foreach (ListViewItem itm in listView1.Items) // Iterate on each Item of the ListView
{
itm.SubItems.Add(line[i++]); // Add the line from your textbox to each ListViewItem using the SubItem
}
否则,Lazyberezovsky的回答同样非常有效,并且是您问题的正确解决方案