2017-03-28 26 views
1

enter image description hereVisual C#:如何將單擊事件附加到列表框中的項目?

見GUI設計上述

我創建其中用戶由姓名,地址,電話,其被存儲在平行陣列進入接觸的程序。 程序然後將所有輸入的聯繫人存儲到列表框中。然後,我希望用戶能夠點擊任何名稱並在相鄰文本框中顯示該人的完整聯繫信息。我的問題是如何創建一個活動,每次點擊列表框中的新項目時,他們的信息都會顯示出來。

回車鍵存儲信息到陣列,並將聯繫人姓名列表:

private void button1_Click(object sender, EventArgs e) 
    { 
     first[mindex] = txtFirst.Text; 
     last[mindex] = txtLast.Text; 
     email[mindex] = txtEmail.Text; 
     address[mindex] = txtAddress.Text; 
     cell[mindex] = txtCell.Text; 

     lstContacts.Items.Add(first[mindex] + " " + last[mindex]); 

     mindex++; 

     txtLast.Text = ""; 
     txtFirst.Text = ""; 
     txtEmail.Text = ""; 
     txtAddress.Text = ""; 
     txtCell.Text = ""; 
     txtLast.Focus(); 

    } 

這是我想每個聯繫人的姓名被點擊時要執行什麼:

private void DisplayContact() 
    { 
     int dispIndex; 
     dispIndex = lstContacts.SelectedIndex; 

     txtOutput.Text = "Name: " + "\t\t" + first[dispIndex] + last[dispIndex] + Environment.NewLine + 
         "Address: " + "\t\t" + address[dispIndex] + Environment.NewLine + 
         "Cell: " + "\t\t" + cell[dispIndex] + Environment.NewLine + 
         "Email: " + "\t\t" + email[dispIndex]; 
    } 

剛不知道如何連接這些東西。任何幫助表示讚賞

回答

2

上的SelectedIndexChanged屬性:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    var i = listBox1.Items[listBox1.SelectedIndex].ToString(); 
    MessageBox.Show(i.ToString()); 

} 
0

你想ListBox中訂閱點擊事件 - 並從那裏你可以叫你DisplayContact方法。

從您的設計視圖中,選擇您想要添加此功能的列表框。在屬性窗口中,單擊閃電圖標以打開「事件」選項卡。

Events Tab

從這裏,滾動,直到你找到單擊操作。雙擊名稱(在本例中爲「Click」),Visual Studio將自動將此控件訂閱到click事件並創建一個方法。

Click Event

在窗體的cs文件,你會發現生成的方法,隨後你可能熟悉的格式。但是,在這裏你打電話給你的DisplayContact方法:

private void listBox1_Click(object sender, EventArgs e) 
    { 
     DisplayContact(); 
    } 

你可以爲你能想到的任何情況下做到這一點 - 但簡單地添加到窗體的代碼的方法是遠遠不夠的,使這個成功的。 Visual Studio中自動生成,它告訴你的程序列表框正在等待該事件的代碼,這種情況發生在窗體的設計文件:

Designer code

^^從FormName.Designer.cs文件,該文件中, InitializeComponent方法。

希望這會有所幫助。

1

您可以使用SelectionChanged事件。將SelectionChanged添加到您的列表框中

private void listBox_SelectionChanged(object sender, EventArgs e) 
{ 
     int dispIndex; 
     dispIndex = lstContacts.SelectedIndex; 

     txtOutput.Text = "Name: " + "\t\t" + first[dispIndex] + last[dispIndex] + Environment.NewLine + 
         "Address: " + "\t\t" + address[dispIndex] + Environment.NewLine + 
         "Cell: " + "\t\t" + cell[dispIndex] + Environment.NewLine + 
         "Email: " + "\t\t" + email[dispIndex]; 
} 

希望它有幫助!

相關問題