Priyank Patel
Priyank Patel

Reputation: 6996

C# array access issue

I am using Asp.net/C# ,, i have declared an integer array as follows public int[] recno; As i dont know the exact size of the array ,, however inside a function i get to know its size based on the number of customer_id's in the table.Here is the function

public void GetRecordNo()
        {
            recid = from id in dt.cust_masters
                    select id;
            recno = new int[recid.Count()];

            for (int i = 0; i < recid.Count(); i++)
            {
                recno[i] = Convert.ToInt32(recid.ElementAt(i).customer_id);
            }

        }

When i try to call a function ShowRecord(int index) which accepts the id of the customer in the following manner

ShowRecord(recno[0])

It gives me an error

Object reference not set to an instance of an object.

Can anybody point me where am i going wrong. Thanks

Upvotes: 0

Views: 150

Answers (4)

Botz3000
Botz3000

Reputation: 39600

First check which object is null by setting a breakpoint and hovering over the parameter recno of ShowRecord(recno[0]). Is it null? If yes, make sure your GetRecordNo() method is actually being called before your call to ShowRecord.

Or use this to access recno:

public int[] RecNo {
    get {
        if (recno == null) { GetRecNo(); }
        return recno;
    }
}

and then use it like

ShowRecord(RecNo[0])

Upvotes: 1

user1082916
user1082916

Reputation:

I think, ShowRecord(int index) contains a parameter which includes int index but when you are calling function,you are using ShowRecord(recno[0]) which means you are passing recno record at index 0.......

Upvotes: 0

Arion
Arion

Reputation: 31239

Why can you just use:

public void GetRecordNo()
{
    var recno=(
        from id in dt.cust_masters
        select id.customer_id
    ).ToArray();
}

Upvotes: 3

Henk Holterman
Henk Holterman

Reputation: 273169

You can simplify your code:

recid = from id in dt.cust_masters
          select id.customer_id;

//recno = new int[recid.Count()];
recno = recid.ToArray();
// remove for-loop

And to find/prevent your null ref problem:

void  ShowRecord(int index)
{
    if (index < 0 || index >= recno.Length)
       throw new InvalidArgumentException("index");

    var id = recno[index];
    ...
}

Upvotes: 3

Related Questions