簡體   English   中英

c#如何從列表框中選擇的內容刪除和編輯信息?

[英]c# how to delete and edit information from selected in listbox?

    string Path = @"C:\Users\Alexander\Desktop\Adressbok\Adressbok.txt";

    List<string> sökhistorik;

    //Lista
    List<Person> Personer = new List<Person>();

    //instans
    Person p1 = new Person();

    public Form1()
    {
        InitializeComponent();
    }
    private void updateUI()
    {
        lstBox.DataSource = null;
        lstBox.DataSource = Personer;
    }
    private void btnSpara_Click(object sender, EventArgs e)
    {
        p1.Namn = tbxNamn.Text;
        p1.Gatuadress = tbxGatuadress.Text;
        p1.Postnummer = tbxPostnummer.Text;
        p1.Postort = tbxPostort.Text;
        p1.Telefonnummer = tbxTelefonnummer.Text;
        p1.Epost = tbxEpost.Text;

        Personer.Add(p1);

        updateUI();

        SaveToFile();

        tbxNamn.Text = "";
        tbxGatuadress.Text = "";
        tbxPostnummer.Text = "";
        tbxPostort.Text = "";
        tbxTelefonnummer.Text = "";
        tbxEpost.Text = "";
    }

我想編輯從列表框中選擇的項目,然后編輯信息並再次保存,然后單擊刪除按鈕並刪除整個信息。 我該怎么做。 我正在使用Windows窗體C#。

為什么不使用BindingList而不是List? BindingList將根據您的來源自動更新您的UI。

假設Person有一個ToString(),

// Bind BindingList to Listbox
public class Form1 {
    BindingList<Person> personer = new BindingList<Person>();
    public Form1() {
        InitializeComponent();
        listBox1.DataSource = personer;
    }


// Remove on button click
private void button1_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex > -1)
    {
        //This automatically updates your listBox
        personer.RemoveAt(listBox1.SelectedIndex);
    }
}

// Update on Button click
private void button2_Click(object sender, EventArgs e)
{
    if (listBox1.SelectedIndex > -1)
    {
        Person p = personer[listBox1.SelectedIndex];
        //Update person here
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM