从文本框到列表视图
本文关键字:列表 视图 文本 | 更新日期: 2023-09-27 18:20:07
我正在开发一个带有多行文本框和listview
的C#应用程序。
文本框内容如下:
John Smith
Joe Bronstein
Susan Jones
Adam Feldman
列表视图有两列:Date
和Name
。
到目前为止,我可以将当前日期放入listview的date列中。接下来,我需要将这些名称复制到"名称"列中。listview
应该是这样的:
Date Name
6/27/2013 John Smith
6/27/2013 Joe Bronstein
6/27/2013 Susan Jones
6/27/2013 Adam Feldman
那么,如何将名称从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}));
工作原理:我们正在枚举TextBox
属性Lines
,该属性逐行返回名称。为每一行创建新的ListViewItem
,并为ListView
中的每一列创建字符串数组。然后项目被添加到listView。
Lazybrezovsky答案非常有效。
但是,如果你已经在Listview
中添加了一个项目,并且你想在添加了Dates
之后添加行(老实说,我对此表示怀疑,但只是猜测)。然后,您需要使用SubItem
将每一行添加到一个新列中。现在,当然,假设您的ListView
具有与Multiline
Textbox
中的Lines
的数量相同的Items
的数量。
所以,你的代码可能看起来是这样的:
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
}
否则,再次Lazybrezovsky的答案非常有效,是您问题的正确解决方案。