terrible-coder
terrible-coder

Reputation: 333

NullReferenceException being thrown

I am a beginner in C#.NET and we were tasked to create an online banking system in which transactions and login data are stored in an array of class. Although I am slowly getting a grasp of the whole array-of-class concept, it seems that I am stuck in saving the login data to an array of class. Here is my program:

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

namespace LabExam1
{
    public partial class Registration : Form
    {
        Transactions trans = new Transactions();
        int number = 10000;
        int x = 0;
        const int size = 100;
        Transactions[] loginData = new Transactions[size];

        public void saveLoginData()
        {
            loginData[x].Username = trans.createUserName(txtFname.Text, txtLname.Text, txtMi.Text);
            loginData[x].Password = txtPass.Text;
            x++;
        }

        public Registration()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            cboType.SelectedIndex = 0;
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            if (txtFname.Text == "" || txtLname.Text == ""|| txtMi.Text == "" || txtPass.Text == "")
            {
                MessageBox.Show("Please fill up all required fields!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                if (cboType.SelectedIndex == 0)
                {
                    number++;
                    loginData[x] = new Transactions();
                    saveLoginData();
                    MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");

                    this.Hide();
                    Transaction tr = new Transaction();
                    tr.ShowDialog();
                }

                if (cboType.SelectedIndex == 1)
                {
                    if (nudDeposit.Value < 2500.00m)
                    {
                        MessageBox.Show("The initial deposit for your account type is insufficient", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    else
                    {
                        number++;
                        loginData[x] = new Transactions();
                        saveLoginData();
                        MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");

                        this.Hide();
                        Transaction tr = new Transaction();
                        tr.ShowDialog();
                    }
                }

                if (cboType.SelectedIndex == 2)
                {
                    if (nudDeposit.Value < 3000.00m)
                    {
                        MessageBox.Show("The initial deposit for your account type is insufficient", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }

                    else
                    {
                        number++;
                        loginData[x] = new Transactions();
                        saveLoginData();
                        MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");

                        this.Hide();
                        Transaction tr = new Transaction();
                        tr.ShowDialog();
                    }
                }
            }      
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

I am getting an error on this part which throws the nullReferenceException:

MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");

Here is my class definition:

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

namespace BankTransaction
{
    public class Transactions
    {
        String username, password;

        #region forArrayOfClassLogin

        public String Password
        {
            get { return password; }
            set { password = value; }
        }

        public String Username
        {
            get { return username; }
            set { username = value; }
        }

        #endregion

        public String createUserName(String fname, String lname, String mi)
        {
            String firstString = fname[0].ToString();
            String secondString = mi[0].ToString();
            String thirdString = lname[0].ToString();

            String uname = firstString + secondString + thirdString;
            return uname;
        }

        public void setBalance(String type, decimal initialBalance)
        {

        }

        public String getUserName()
        {
            return username;
        }

        public String setPassword(String pass)
        {
            return password = pass;
        }

        public String getPassword()
        {
            return password;
        }
    }
}

Any help would be greatly appreciated. Thanks in advance.

Upvotes: 0

Views: 122

Answers (6)

vijay as vj
vijay as vj

Reputation: 69

The Think is whenever we getting null reference .. it mean that it has not memory for that .. so debug each and every line you can find the solution for that .. otherwise before using the properties put null check condition

Upvotes: 0

Rik
Rik

Reputation: 29243

loginData[x] = new Transactions();
saveLoginData();
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");

The problem here is that the call to saveLoginData() increments the value of x, so when you show the MessageBox, the you're pointing to the next element in loginData, which is uninitialized.

This is a good illustration as to why you should be wary of using global variables. It's not obvious saveLoginData would modify x, which is probably why you made the mistake in the first place.

Also, if this weren't an exercise, I would recommend using List<Transactions> instead of an array, because it makes adding elements easier; you don't have to keep track of the number of elements yourself.

Finally, this fragment appears several times in your code:

number++;
loginData[x] = new Transactions();
saveLoginData();
MessageBox.Show("Generated Username: " + loginData[x].Username + number + "\n" + "Please do not share this Information to anyone!");

this.Hide();
Transaction tr = new Transaction();
tr.ShowDialog();

It would be better to turn this into a method which you would then call several times.

Upvotes: 0

Pushkar
Pushkar

Reputation: 112

The issue seems to be in line "x++;" in the function saveLoginData().

You are declaring the X as member level variable, with X=0.

And as you increment the value of x in "saveLoginData()" function it becomes X=1, then while trying to access the array in parent function, the value of X is 1 now, but your array does not has any value stored for that index, which results in the exception.

Upvotes: 1

Abin
Abin

Reputation: 2956

String firstString = fname[0].ToString();
String secondString = mi[0].ToString();
String thirdString = lname[0].ToString();

insted of above line try doing

String firstString = fname;
String secondString = mi;
String thirdString = lname;

Please refer below link for more details. http://msdn.microsoft.com/en-us/library/ms228362.aspx

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You need to use loginData[x -1] as you have increment the value of x in saveLoginData()

MessageBox.Show("Generated Username: " + loginData[x -1].Username + number + "\n" + "Please do not share this Information to anyone!");

Upvotes: 1

Jon Egerton
Jon Egerton

Reputation: 41539

In saveLoginData you're doing x++ at the end,

When you refer to loginData[x].Username in your message, x is not the same as it was when you setup loginData[x] = new Transactions(); and so loginData[x] will be null at that moment.

Upvotes: 0

Related Questions