2012-01-01 88 views
2

干杯,插入数据库值到字符串数组 - 不工作

我试图插入数据库值到我的字符串数组。

出于某种原因,它说:

“对象引用不设置到对象的实例。”

这是我的代码:

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

其指的这条线:

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

谢谢你的助手!

+0

你应该绝对正确地处理连接和命令对象(如果你打算使用它,阅读器也是如此)。在小规模测试中,这似乎可行,但您将很快在服务器上耗尽资源(连接)。 – Lucero 2012-01-01 17:06:24

回答

3

RND为空,在您的活动

+0

谢谢,帮了很多! – thormayer 2012-01-01 17:11:35

1
rnd = new Random(); 

如上实例化rnd开始添加一行

rnd = new Random();

。您正在使用导致您的问题中的异常被抛出的null对象。