如何递增整数数组的索引值
本文关键字:索引值 数组 整数 何递增 | 更新日期: 2023-09-27 18:36:51
我想将值从数据库表存储到数组.但是当我这样做时,异常"对象引用未设置对象的实例"通过请查看我的代码。
.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[] 同意;
}
test.agree
null
.
您需要在字段中放置一个新数组。
您究竟在哪里得到错误,在哪个阵列上? 从外观上看,它必须在 agree[] 上,你永远不会实例化。
尝试
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());
在添加值之前实例化:
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"]);
}