-1

I have a Code where i am getting data from csv file on name search if i type name in textbox1 then deatails related to that person are displayed in the remaining textboxes like surname , city , state

error :error screenshot 1: https://i.stack.imgur.com/VdVEZ.png enter image description here Download link of my project : Link 1: https://www.sendspace.com/file/76vdv5

Code i have written

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace studentdetails
{
    public partial class Form1 : Form
    {
        String filePath = "C:\\Users\\vikas\\Desktop\\d.csv";
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            String con_env = textName.Text.ToString();
            UserDetails ud = SearchFor(con_env);
            textSurname.Text = ud.surname;
            textCity.Text = ud.city;
            textState.Text = ud.state;
        }

        UserDetails SearchFor(String searchName)
        {
            var strLines = File.ReadLines(filePath);
            foreach (var line in strLines)
            {
                var bits = line.Split(',');
                if (bits[0].Equals(searchName))
                {
                    return new UserDetails()
                    {           
                        surname = bits[1],
                        city = bits[2],
                        state = bits[3],                     
                    };
                }
            }
            return null;
        }
}
}

Userdetails Clas

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace studentdetails
{
    class UserDetails
    {
        public string firstname { get; set; }
        public string surname { get; set; }
        public string city { get; set; }
        public string state { get; set; }
    }
}

Can anyone figure out why this error occurring

Object reference not set to an instance of an object.

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
fedrick
  • 1
  • 2

3 Answers3

0

If you look at your code your returning null from the method call below

UserDetails ud = SearchFor(con_env);

You then try to access a field from that object which is null

textSurname.Text = ud.surname;

You need to return the UserDetails that you are reading from the file

0

This error occurs when your object is not initialized. In your case this error occurred while initializing UserDetails ud.

If you debug, you will realize you are returning instance of UserDetails from SearchFor() function.

When bits[0].Equals(searchName) matches at that time it is returning instance of UserDetails, but when this condition failed for all records in foreach then it is returning null which is not acceptable.

To resolve this issue instead of returning null from SearchFor() function, pass instance of UserDetails with default parameters.

Something like,

 UserDetails SearchFor(String searchName)
        {
            var strLines = File.ReadLines(filePath);
            foreach (var line in strLines)
            {
                var bits = line.Split(',');
                if (bits[0].Equals(searchName))
                {
                    return new UserDetails()
                    {           
                        surname = bits[1],
                        city = bits[2],
                        state = bits[3],                     
                    };
                }
            }
            return new UserDetails()
                    {           
                        surname = "Default text",
                        city = "Default text",
                        state = "Default text",                     
                    }; //Here you need to fix
        }

If you do something like above solution, then for failed condition it will set values of Surname, City and state to Default text which is not correct. To avoid this situation, you can put null check before assigning values to text box

    private void Form1_Load(object sender, EventArgs e)
    {
        String con_env = textName.Text.ToString();
        UserDetails ud = SearchFor(con_env);
        //if ud is null then do not set values to text box
        if(ud != null)
        {
           textSurname.Text = ud.surname;
           textCity.Text = ud.city;
           textState.Text = ud.state; 
        }
       else  //else block to set default value
       {
          textSurname.Text = "Default value";
           textCity.Text = "Default value";
           textState.Text = "Default value"; 

        }   
    }


    UserDetails SearchFor(String searchName)
    {
        var strLines = File.ReadLines(filePath);
        foreach (var line in strLines)
        {
            var bits = line.Split(',');
            if (bits[0].Equals(searchName))
            {
                return new UserDetails()
                {           
                    surname = bits[1],
                    city = bits[2],
                    state = bits[3],                     
                };
            }
        }
        return null;
    }
Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
  • can you correct my code and send me or tell me where do i need to add code so that it works for me – fedrick May 04 '19 at 05:07
  • prasad T working but when i search name in textbox1 as ram the remaing details of that user is not fetched automatically and shown in respected textbox2,textbox3,textbox4 – fedrick May 04 '19 at 05:12
  • This is my project Download link of my project : Link 1: https://www.sendspace.com/file/76vdv5 can you correct it for me since two days i am struggling as i am new to c# – fedrick May 04 '19 at 05:17
  • And even all the people in forum special thanks for helping me out ... – fedrick May 04 '19 at 06:13
  • prasad one more dout how do i set the textbox2,textbox3,textbox4 to default values if i search in textbox 1 then only the default should be replaced with original value form csv file – fedrick May 04 '19 at 06:18
  • Kindly check latest update, I added else block where you can set default values if search in textbox1 is not available. – Prasad Telkikar May 04 '19 at 06:26
  • Please remove unnecessary comments, it may divert other users.. btw I liked god saver.. comment you can keep it... ;) – Prasad Telkikar May 04 '19 at 06:26
0

I did mention in my previous answer (when I gave this code) that the SearchFor method returns a null if the user is not found - when you do your search, and before you try to use the result, you should check if the return value is null. Something like:

UserDetails ud = SearchFor(con_env);
if(ud != null){
  surnameTextbox.Text = ud.Surname;
  ...
} else {
  MessageBox.Show("user not found");
}

Also note that you seem to have forgotten to set the name property of the userdetails object. Check the code i gave in the last answer. Also you should make the properties of the UserDetails class have Names Like This: Surname, City.. "public properties have names starting with a capital letter" is the rule in c# and if you're learning you should get used to doing it now

Caius Jard
  • 72,509
  • 5
  • 49
  • 80