Note that there are some explanatory texts on larger screens.

plurals
  1. POsaving data from datagrid c#
    primarykey
    data
    text
    <p>hi guys i am new to c# and i was making a text editor program using data grid view. The problem is when i open a text file to my data grid, then when i press save i get the error saying "Index was outside the bounds of the array". I included my code below. Any suggestions can be a big help for me. I included my code below. </p> <pre><code> // 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 &lt;= dataGridView1.Rows.Count - 1; r++) { for (int c = 0; c &lt;= 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 &lt;= dataGridView1.Rows.Count - 1; r++) { for (int c = 0; c &lt;= 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); } } </code></pre> <p>Thanks again for the help</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload