2015-04-04 75 views
-2

所選項目如何獲得行號從列表視圖中選擇的項目在C#獲取行號從列表視圖C#

private void listView1_DoubleClick(object sender, EventArgs e) 
{ 
    if((listView1 row numer for selectitem) > 2) 
    { 
     int indx = listView1.SelectedItems[0].Index; 
     listView1.Items[indx].Remove(); 
    } 
} 
+0

你的意思是問如何獲得索引? https://msdn.microsoft.com/en-us/library/system.windows.forms.listview.selectedindices(v=vs.110).aspx – 2015-04-04 10:37:38

+0

如果我選擇項目我需要得到行號爲這個選擇 – 2015-04-04 10:57:05

回答

0

嘗試SelectedIndexChanged事件,而不是...指數位置是從零開始的,所以如果你有10個項目的指標將是0 - 9。如果你想0是那麼行1只需添加一個。最後,當沒有選擇的項指數爲-1

private void ListView1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (ListView1.SelectedIndex > -1) 
    { 
     // Add 1 so you have 1 - 10 instead of 0 - 9 
     int rowNumber = ListView1.SelectedIndex + 1; 

     // Your example says you want to delete the selected index 
     // so you still would want to use the selected index 
     ListView1.Items.RemoveAt(ListView1.SelectedIndex); 

     // After you remove the item, this method will fire again 
     // but the selected index will be -1 so none of this code will 
     // execute again. 
    } 
} 

請記住,此代碼只支持一次選擇一行。

希望這有助於...

0

https://msdn.microsoft.com/en-us/library/system.windows.forms.listview.itemselectionchanged(v=vs.110).aspx可能會有所幫助。

也就是說,請監聽ItemSelectionChanged事件,並在事件數據上使用ItemIndex屬性。

E.g.微軟的例子顯示

private void ListView1_ItemSelectionChanged(
    Object sender, ListViewItemSelectionChangedEventArgs e) { 

    var i = e.ItemIndex; // got the latest selection 
} 
+0

謝謝但如果您在列表視圖中選擇任何項目,需要該項目的門禁行號,請選擇 – 2015-04-04 10:54:34

+0

嘗試更新答案以反映我認爲您所要求的內容。我很抱歉地說語言障礙很高 - 我不完全瞭解你的英語,並且在猜測你的意圖。 – 2015-04-04 14:28:55