2013-03-09 61 views
0

我有一個Windows的方法窗體應用程序,PaymentInfo,該列表視圖後填充從子項的標籤在listView1已被填充:選擇列表視圖項編程工作不

internal void PaymentInfo() 
{ 
     label3.Text = "Amount Paid: " + listView1.SelectedItems[0].SubItems[1].Text.ToString(); 
     label3.Refresh(); 
     label6.Text = "Payment Type: " + listView1.SelectedItems[0].SubItems[5].Text.ToString(); 
     label6.Refresh(); 
} 

listView1填充,我嘗試使用要調用的方法如下:

listView1.Items[0].Selected = true; 
listView1.Items[0].Focused = true; 
PaymentInfo(); 

這實際上在選擇列表中的第一個項目,但是當它試圖運行PaymentInfo,我在那開始線得到,詳細信息

「InvalidArgument ='0'的值對'index'無效。

我也打電話給PaymentInfo與listView1_MouseClick,它工作正常。我檢查了一些其他的東西,並注意到即使我以編程方式選擇該項目,SelectedItems.Count返回0。爲什麼會這樣?謝謝!

+0

包括PaymentInfo()的代碼。漂亮嗎? – 2013-03-09 22:53:51

+1

嘗試調用PaymentInfo()之前的listView1.Select() – 2013-03-09 22:56:30

+0

爲什麼以編程方式選擇一個項目?只有這個功能應該起作用,或者爲了視覺上的原因呢? – Steve 2013-03-09 23:01:16

回答

1

不確定原因,但唯一可行的方法是將代碼放入Load事件中。

private void PastPayment_Load(object sender, EventArgs e) 
    { 
     listView1.Items[0].Selected = true; 
     listView1.Items[0].Focused = true; 
     PaymentInfo(); 
     PopDetails(); 
     this.listView1.SelectedIndexChanged += listView1_SelectedIndexChanged; 
    }