Search code examples
c#winformsmessagebox

How do i display Name by getting ID?


i ask the user what's his/her voter's id and if it is in my list, the program shows a messagebox displaying his/her name. and then if the user presses "ok" it redirects to another form.

here is my code:

public class Voter{
        public string voterName {get; set;}
        public int voterID {get; set;}

        public override string ToString()
        {
            return "   Name: " + voterName;
        }
        }
void BtnValidateClick(object sender, EventArgs e)
    {
        int id = Int32.Parse(tbVotersID.Text);
        List<Voter> voters = new List<Voter>();
        voters.Add(new Voter() {voterName = "voter #1", voterID = 12345});
        voters.Add(new Voter() {voterName = "voter #2", voterID = 67890});
        voters.Add(new Voter() {voterName = "voter #3", voterID = 11800});

        if (voters.Contains(new Voter {voterID = id})){

        //prompts a messagebox that shows voterName
            }
        else{
        MessageBox.Show("ID not recognized.", "ID ENTRY", MessageBoxButtons.OK, 
        MessageBoxIcon.Error);
        }

    }

Solution

  • You can use LINQ with Find() to get the first result's voterName. Check if its null, if it's not, show the MessageBox(). https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.find?view=netframework-4.8

    void BtnValidateClick(object sender, EventArgs e)
    {
        int id = Int32.Parse(tbVotersID.Text);
        List<Voter> voters = new List<Voter>();
        voters.Add(new Voter() {voterName = "voter #1", voterID = 12345});
        voters.Add(new Voter() {voterName = "voter #2", voterID = 67890});
        voters.Add(new Voter() {voterName = "voter #3", voterID = 11800});
    
    
        var voterName = voters.Find(voter => voter.voterID == id)?.voterName;
        if (!string.IsNullOrEmpty(voterName)){
                MessageBox.Show(voterName);
            }
        else{
        MessageBox.Show("ID not recognized.", "ID ENTRY", MessageBoxButtons.OK, 
        MessageBoxIcon.Error);
        }
    
    }