首页 > 解决方案 > C# WPF Retrieve Items from Listview?

问题描述

Right now I am using my Database data to fill the Listview. But I need to edit the data as well. So I want to select the item in the list and be able to put it into a string. I am testing this with a messagebox but the following keeps happening with this code:

//Fill Listview with MySql Data
    public void Data()
    {
        _NAWGEGEVENS = Connect.Fill();
        foreach (var _NAW in _NAWGEGEVENS)
        {


            test.Add(new NAWGegeven()
            {
                Voornaam = _NAW.voornaam,
                Achternaam = _NAW.achternaam,
                Geslacht = _NAW.geslacht,
                Adres = _NAW.geslacht,
                Huisnummer = _NAW.huisnummer,
                Postcode = _NAW.postcode,
                Woonplaats = _NAW.woonplaats,
                Geboortedatum = _NAW.geboortedatum
            });
        }
        LVNAV.ItemsSource = test;
    }
//retrieve item from the list
    private void BtnWijzigen_Click(object sender, RoutedEventArgs e)
    {
        string text2;
        text2 = ((NAWGegeven)LVNAV.SelectedValue).ToString();
        //String text = LVNAV.SelectedItem.ToString();
        MessageBox.Show(text2);
    }
//CLASS for the listview
class NAWGegeven
{
    public string Voornaam { get; set; }
    public string Achternaam { get; set; }
    public string Geslacht { get; set; }
    public string Adres { get; set; }
    public int Huisnummer { get; set; }
    public string Postcode { get; set; }
    public string Woonplaats { get; set; }
    public DateTime Geboortedatum { get; set; }

}

The outcome is always the same, it is the following message: ERP.NAWGEGEVEN Does anyone have an idea how to retrieve the selected item from the listview? I want it to retrieve the ID of the record from the List which is loaded with the Records from the database.

I did this before with Listboxes, but since the tabs get all messed up I decided to switch to listviews. I am kinda new to this.

标签: c#wpflistview

解决方案


如果我理解您的问题,您没有从 ToString 方法获得预期的字符串。如果你想让你的 ToString 方法输出一个特定格式的字符串,你需要在你的 NAWGegeven 类中重写 ToString 方法。

class NAWGegeven
{
    public string Voornaam { get; set; }
    public string Achternaam { get; set; }
    public string Geslacht { get; set; }
    public string Adres { get; set; }
    public int Huisnummer { get; set; }
    public string Postcode { get; set; }
    public string Woonplaats { get; set; }
    public DateTime Geboortedatum { get; set; }

    public override string ToString()
    {
        //your formatted output string here
        //Example
        return $"{nameof(Voornam)}: {Voornam}, {nameof(Achternaam)}: {Achternaam}";
    }

}

编辑:如果您要检索特定属性,您的调用应该看起来更像这样:

((NAWGegeven)LVNAV.SelectedValue).[你想要的属性].ToString();


推荐阅读