大家好我是c#的新手,我正在使用数据网格视图制作文本编辑器程序。问题是当我打开文本文件到我的数据网格,然后当我按下保存时我得到错误说“索引超出了数组的范围”。我在下面提供了我的代码。任何建议对我来说都是一个很大的帮助。我在下面提供了我的代码。
// edit file button
dataGridView1.Columns.Add("colname", "Question");
dataGridView1.Columns.Add("colname", "Answer 1");
dataGridView1.Columns.Add("colname", "Answer 2");
dataGridView1.Columns.Add("colname", "Answer 3");
dataGridView1.Columns.Add("colname", "Answer 4");
dataGridView1.Columns.Add("colname", "Correct Answer");
dataGridView1.Columns[5].ReadOnly = true;
dataGridView1.Columns[5].DefaultCellStyle.BackColor = Color.DimGray;
dataGridView1.AllowUserToAddRows = true;
StreamReader sr = new StreamReader(fName);
string Contents = sr.ReadToEnd();
string[] strArray = { Contents };
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
dataGridView1.Rows.Add(strArray[r].Split('|')); //getting the error here
}
}
//save button
private void button2_Click(object sender, EventArgs e)
{
//dataGridView1.AllowUserToAddRows = false;
if (dataGridView1.Visible)
{
string fName = "C:\\Documents and Settings\\" + txtFileName.Text + ".txt";
System.IO.StreamWriter file = new System.IO.StreamWriter(fName);
string sLine = "";
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
sLine = sLine + "|";
}
}
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Save Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = "";
dataGridView1.Visible = false;
}
else
{
string cap = "Confirmation";
string message = "Nothing to save";
MessageBoxButtons Btn2 = MessageBoxButtons.OK;
MessageBox.Show(message, cap, Btn2);
}
}
再次感谢您的帮助
答案 0 :(得分:0)
最初有一个dataGridView1.Rows.Count
在循环内部你这样做 dataGridView1.Rows.Add,每次将dataGridView1.Rows.Count递增1
所以它在处理后回到循环中
try declaring int gridRowcount = dataGridView1.Rows.Count;
and then replace (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
for (int r = 0; r <= gridRowcount - 1; r++) and try
猜猜