0

我想将值从数据库表存储到数组。但是当我这样做时,异常“对象引用未设置对象实例”通过请查看我的代码。

.cod 背后

   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"]);

    }

业务逻辑层类代码:

公开课测试{

public static int[] 同意;

}

4

3 回答 3

2

test.agreenull

您需要在该字段中放置一个新数组。

于 2012-06-11T11:42:17.870 回答
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());
于 2012-06-11T11:44:16.960 回答
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"]);
        }
于 2012-06-11T12:14:06.990 回答