我想将对象列表保存到xml。我还使用gridView在列表中显示对象。我正在使用xml.serialization库。从xml保存是可以的,没有错误。在我加载文件后,对象出现在列表中,但我得到的错误索引是OutOfRange。我无法找到问题所在。
有错误:
System.ArgumentOutOfRangeException:索引超出范围。必须是非负数且小于集合的大小。
参数名称:索引
在System.Collections.ArrayList.get_Item(Int32索引)
在System.Windows.Forms.DataGridViewSelectedRowCollection.get_Item(Int32 index)
我的主要声明:
private Teams team1, team2;
DataTable tQues = new DataTable(), tAnsw = new DataTable();
List<Question> ques = new List<Question>(); private bool edQues = false;
private int quesSelected = -1;
List<Answers> answ = new List<Answers>(); private bool edAnsw = false;
private int answSelected = -1;
班级Question
:
public class Question
{
public static int nextID = 1;
public int questionID;
public String text;
public int maxPoints;
public int answersCount = 0;
public int pointsCount = 0;
public bool played = false;
public Question()
{
this.questionID = nextID++;
}
public Question(String text, int maxPoints)
{
this.questionID = nextID++;
this.text = text;
this.maxPoints = maxPoints;
}
public static void Save(List<Question> list)
{
using (var file = new FileStream("Questions.xml", FileMode.Create)) {
XmlSerializer xml = new XmlSerializer(typeof(List<Question>));
xml.Serialize(file, list);
}
}
public static List<Question> Load()
{
using (var file = new FileStream("Questions.xml", FileMode.Open))
{
XmlSerializer xml = new XmlSerializer(typeof(List<Question>));
return (List<Question>) xml.Deserialize(file);
}
}
}
我从文件中加载了对象列表。
private void fMain_Load(object sender, EventArgs e)
{
if (File.Exists("Questions.xml"))
{
ques = Question.Load();
}
//add columns to ques
tQues.Columns.Add("id", typeof(int));
tQues.Columns.Add("intrebarea", typeof(String));
tQues.Columns.Add("maxPoints", typeof(int));
tQues.Columns.Add("played", typeof(String));
// add columns to answ
tAnsw.Columns.Add("id", typeof(int));
tAnsw.Columns.Add("questionid", typeof(int));
tAnsw.Columns.Add("teamid", typeof(int));
tAnsw.Columns.Add("text", typeof(String));
tAnsw.Columns.Add("points", typeof(int));
//open queries
OpenQues();
OpenAnsw();
}
我将对象加载到网格:
private void OpenQues()
{
tQues.Clear();
foreach (Question i in ques)
{
tQues.Rows.Add(i.questionID, i.text, i.maxPoints, i.played ? "yes" : "no");
}
gridQuestions.DataSource = tQues;
gridQuestions.Columns[0].Visible = false;
}
我有错误(第70行):
private void setQuesSelected()
{
if (gridQuestions.Rows.Count > 0)
foreach (Question i in ques)
{
/*70 line*/if (Convert.ToInt32(gridQuestions.Rows[gridQuestions.SelectedRows[0].Index].Cells[0].Value) == i.questionID)
{
quesSelected = ques.IndexOf(i);
break;
}
}
else
quesSelected = -1;
}
答案 0 :(得分:1)
在你的情况下,gridQuestions.SelectedRows[0].Index
等于-1或SelectedRows
为空,因为你没有选择行