2

Cheers,

Im trying to insert a database value to my string array.

for some reason, it says :

"Object reference not set to an instance of an object."

This is my code :

if (IsPostBack)
{
    if (RadioWords.Checked == true)
    {
        con = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Daniel;Integrated Security=True");
        con.Open();

        string SqlCount = "SELECT COUNT(*) FROM WordGame";

        SqlCommand command = new SqlCommand(SqlCount, con);

        //Sets an array of the size of the database.
        int count = (Int32)command.ExecuteScalar();
        arrOfWords = new string[count];

        //Initialize the words in the array.
        for (int i = 0; i < arrOfWords.Length; i++)
        {
            int GetRandomNumber =  rnd.Next(1, arrOfWords.Length);

            string Sqlinsert = "SELECT Word FROM WordGame WHERE ID='"+GetRandomNumber+"'";

            SqlCommand commandToRandom = new SqlCommand(Sqlinsert, con);

            arrOfWords[i] = commandToRandom.ExecuteScalar().ToString();
        }
    }

and its refering to this line :

int GetRandomNumber =  rnd.Next(1, arrOfWords.Length);

Thanks for the helpers!

1
  • You should absolutely properly dispose the connection and command objects (and if you plan on using one, the reader too). In a small-scale test this will seem to work, but you're going to run out of resources (connections) very quickly on a server. Commented Jan 1, 2012 at 17:06

2 Answers 2

3

rnd is null , add a line

rnd = new Random();

at the start of your event

Sign up to request clarification or add additional context in comments.

Comments

1
rnd = new Random();

Instantiate rnd as above. You're using a null object that causes the exception in your question to be thrown.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.