Click here to Skip to main content
15,566,625 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How to assign values to struct array by calling a function whose return type is struct.


What I have tried:

<pre lang="C#"><pre> 
.
.
.
acccode = 120101000001; widget = 1;
            result = ebis.ReadData(conn, acccode);
            for (int i = 0; i < result.Count; i++)
            {
                UserProfile details = (UserProfile)result[i];               
                details.metric[i] = ebis.ReadDBData(conn, details.usercode, "120101000001");//here an error is showing "An unhandled exception of type 'System.NullReferenceException' occurred in eBis Application.exe
"
                
            }


//this is the code in main application. ReadDBData is the method in a class

C#
<pre> <pre> <pre>  public Metric ReadDBData(MySqlConnection connection, string usercode, string accode)
        {

            int count = 0;
            ArrayList userDataList = new ArrayList();
            Metric[] usermetric;

            command = new MySqlCommand("SELECT SUM(d.amt) Amount, MAX(d.CREATED_DATE) createddate, MAX(d.MODIFIED_DATE) modifieddate FROM ddata d, branchuser b, userprofile p WHERE d.acccode = '" + accode + "' AND d.br = b.BRCODE  AND b.USERCODE = p.CODE AND cancel = 'No' and b.USERCODE='" + usercode + "' GROUP BY b.USERCODE;", connection);
            adapter = new MySqlDataAdapter(command);
            adapter.Fill(dt);
            int i;
            count = dt.Rows.Count;
            usermetric = new eBisExtension.Metric[count];
            for (i = 0; i < dt.Rows.Count; i++)
            {
                usermetric[i] = new Metric
                {
                    code = accode,
                    amount = Convert.ToDouble(dt.Rows[i]["Amount"].ToString()),
                    amountstring = Convert.ToString("{\"value\":" + dt.Rows[i]["Amount"].ToString() + "}")
                };
                return usermetric[i];
            }
            return usermetric[count];
        }





//metric is the structure in another structure
C#
 public struct Metric
    {
        public string code;
        public double amount;
        public string amountstring;
    };

public struct UserProfile
    {
        public string usercode;
        public string name;
        public string group;
        public string password;
        public string email;
        public Metric[] metric;
    };
Posted
Updated 3-Feb-21 21:05pm
v2
Comments
Richard Deeming 4-Feb-21 7:27am    
REPOST
This is the same question you posted last week:
How to assign values to struct array in another struct dynamically[^]

The answer hasn't changed in the last five days.
Member 12453921 4-Feb-21 23:29pm    
yes..but i get an error in main application..plz help me... i want to complete my project immediately. thanks in advance
Richard Deeming 5-Feb-21 3:34am    
Your question has already been answered. Posting the same question again serves no purpose.

If you're getting a different error, then you need to post a different question, including the full details of the error.

1 solution

Let's start with the serious one that you haven't spotted: Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Now let's look at the one you have spotted, before we go back to another problem you will get soon enough. Null reference exception: This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterday's shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values. At a guess, result is null, but that needs the debugger to confirm, and then to find out why.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!

And now, the really big and nasty one!
structs are value types - which means that they are copies of data not references to them: just like an integer every time you use a struct to get a copy of the value:
C#
UserProfile details = (UserProfile)result[i];
details will get exactly the same data that the array element held, but changed you make to it will not be reflected back into the original.
That's complicated, but this may help: Using struct and class - what's that all about?[^]
You need to be very, very careful when using struct types, particularly in arrays as the data you deal with is very likely to be a copy rather than the original!
 
Share this answer
 
Comments
Richard Deeming 4-Feb-21 7:27am    
He didn't spot it when you warned him about it last week either. :)
How to assign values to struct array in another struct dynamically[^]
OriginalGriff 4-Feb-21 8:17am    
Clearly a fast learner ... :sigh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900