对象引用设置为空C#应用程序

时间:2019-05-04 04:48:13

标签: c#

我有一个代码,可以在名称搜索中从csv文件获取数据 如果我在textbox1中键入name,则与该人相关的详细资料将显示在其余的文本框中,例如surname,city,state

错误:error screenshot 1https://i.stack.imgur.com/VdVEZ.png enter image description here 我的项目的下载链接: Link 1https://www.sendspace.com/file/76vdv5

我写的代码

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;
        }
}
}

用户详细说明

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; }
    }
}

谁能找出导致此错误的原因

对象引用未设置为对象的实例。

3 个答案:

答案 0 :(得分:2)

如果您查看代码,则可以从下面的方法调用中返回空值

UserDetails ud = SearchFor(con_env);

然后您尝试从该对象访问一个为空的字段

textSurname.Text = ud.surname;

您需要返回从文件中读取的UserDetails

答案 1 :(得分:0)

未初始化对象时发生此错误。对于您而言,此错误是在初始化UserDetails ud时发生的。

如果进行调试,您将意识到您正在从UserDetails函数返回SearchFor()的实例。

bits[0].Equals(searchName)当时匹配时,它将返回UserDetails的实例,但是当foreach中的所有记录的此条件失败时,它将返回null,这是不可接受的。

要解决此问题,而不是从SearchFor()函数返回null,请使用默认参数传递UserDetails的实例。

类似

 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
        }

如果您执行上述解决方案,则在失败情况下,会将Surname, City and state的值设置为Default text,这是不正确的。为避免这种情况,可以在将值分配给文本框之前放空检查

    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;
    }

答案 2 :(得分:0)

我在上一个答案中(当我给出此代码时)确实提到,如果找不到用户,SearchFor方法将返回null-在执行搜索时,以及尝试使用结果之前,应检查是否返回值为null。像这样:

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

还要注意,您似乎忘记了设置userdetails对象的name属性。检查我在最后一个答案中给出的代码。同样,您还应该使UserDetails类的属性具有类似这样的名称:Surname,City ..“公共属性的名称以大写字母开头”是c#中的规则,如果您要学习的话,现在就应该习惯