如何在c#的listview项中的特定行中插入数据?

时间:2017-08-26 17:56:39

标签: c# listview

我有listView。我想在第一行,第二列添加数据。我尝试过以下方法:

listView1.Items[0].Subitems[1].Text = "my data";

我收到错误,因为'0'不是有效的索引。然后我尝试了这个:

if (listViewDownloadList.SelectedItems.Count == -1)
        {
            listViewDownloadList.Items[0].SubItems[1].Text = "Hello";
        }

现在,什么也没发生。没有插入,没有错误。

但它不起作用。你能帮帮我吗?

2 个答案:

答案 0 :(得分:1)

您收到错误' 0'不是有效索引,因为列表视图没有任何元素。 首先,您需要创建一个如下所示的行 -

<button 
 (click)="onProductAdded(product)"
 *ngIf="!productIsOnImportList"
 class="ui labeled icon blue button">
 <i class="plus icon"></i>
  Add to Import List
</button>
<button 
 (click)="onProductRemoved(product)"
 *ngIf="productIsOnImportList"
 class="ui labeled icon red button">
 <i class="minus icon"></i>
  Remove 
</button>

然后你需要将该行添加到listview中,如下所示 -

 string[] row = { "Hello" };
 var listViewItem = new ListViewItem(row); 

答案 1 :(得分:0)

您只能在subitem中向{strong>现有项添加listView,如下所示:

listView1.Location = new System.Drawing.Point(20, 20);
listView1.Width = 250;

// The View property must be set to Details for the 
// subitems to be visible.
listView1.View = View.Details;

// Each SubItem object requires a column, so add three columns.
this.listView1.Columns.Add("Key", 50, HorizontalAlignment.Left);
this.listView1.Columns.Add("Co1 1", 100, HorizontalAlignment.Left);
this.listView1.Columns.Add("Col 2", 100, HorizontalAlignment.Left);


// Add a ListItem (row1) object to the ListView.
ListViewItem row1 = new ListViewItem();
row1.Text = "Row 1";
row1.SubItems.Add("A");
row1.SubItems.Add("");
listView1.Items.Add(row1);


// Add a ListItem (row2) object to the ListView.
ListViewItem row2 = new ListViewItem();
row2.Text = "Row 2";
row2.SubItems.Add("");
row2.SubItems.Add("B");

listView1.Items.Add(row2);


// Add a SubItem to existing item (row1)
System.Windows.Forms.ListViewItem.ListViewSubItem item1 = new ListViewItem.ListViewSubItem();
item1.Text = "C";

listView1.Items[0].SubItems[2] = item1;

<强>结果

listView