2012-06-11 46 views
0

我想將數據庫表中的值存儲到數組中,但是當我這樣做時,請通過查看我的代碼來發現異常「object eferance not set object of instance」。如何增加整數數組的索引值

程序.cod Behinde

public DataSet showoption1() 
    { 
     SqlCommand cmd = new SqlCommand("select * from assessmenttest",con); 

     SqlDataAdapter adptr = new SqlDataAdapter(cmd); 

     DataSet ds = new DataSet(); 
     adptr.Fill(ds,"test"); 

     int [] arr=new int[10]; 
     DataTable table=ds.Tables[0]; 
     for(int i=0;i<table.Rows.Count;i++ ) 
     { 
test.Agree[i] =Convert.ToInt32(ds.Tables[0].Rows[i]["option1"]); 

    } 

業務邏輯層類代碼:

公共類測試{

公共靜態INT []同意;

}

+0

可能測試或test.agree未初始化......但爲什麼你使用數組? – Reniuz

+0

你確定'行[i]'包含''option1''嗎?你可能想嘗試一個'foreach'聲明而不是連續的項目,以犧牲你得到你所期望的。 –

回答

2

test.agreenull

您需要在該字段中添加一個新數組。

1

你究竟在哪裏得到錯誤,哪個數組?從外觀上看,它必須位於你從未實例化過的同意[]上。

嘗試

public static int[] agree =new int[10]; 

但我想你可能要做出同意的列表,因爲你不知道你需要多少

public static List<int> agree = new List<int>; 

然後使用

agree.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["option1"]); 

和你可以像訪問數組一樣訪問它

MessageBox.Show(agree[1].ToString()); 
0

實例化增加值之前:

SqlCommand cmd = new SqlCommand("select * from assessmenttest", con); 

     SqlDataAdapter adptr = new SqlDataAdapter(cmd); 

     DataSet ds = new DataSet(); 
     adptr.Fill(ds, "test"); 

     int[] arr = new int[10]; 
     DataTable table = ds.Tables[0]; 
     test.agree = new int[table.Rows.Count]; 
     for (int i = 0; i < table.Rows.Count; i++) 
     { 

      test.agree[i] = Convert.ToInt32(ds.Tables[0].Rows[i]["option1"]); 
     }