简体   繁体   中英

There is no last entered value taken from dataGridView

FileStream fs = new FileStream(@"file.txt", FileMode.Create);
StreamWriter streamwriter = new StreamWriter(fs);

try
{
    for (int j = 0; j < dataGridView1.Rows.Count -1 ; j++)
    {
        for (i = 0; i < dataGridView1.Rows[j].Cells.Count; i++)
        {
            streamwriter.Write(dataGridView1.Rows[j].Cells[i].Value + "#");
        }

        streamwriter.WriteLine("\n");
    }

    streamwriter.Close();
    fs.Close();
    MessageBox.Show("File saved successfully!");
}
catch
{
    MessageBox.Show("File save failed!");
}

This function should transfer the values from the DataGridView to the file but the last value is not constantly written. I realized that it deletes the last element I entered

It should be like this:

Name1#Lastname1#Number1#Home1#

This is real result:

Name2#Lastname2#Number2##

The problem is in your loop iterating over rows, right now your condition is

j < dataGridView1.Rows.Count -1

This means if the row count is 10, your loop will go through indexes 0 to 8, and skip index 9.

You should change your condition to

j < dataGridView1.Rows.Count

The posted code will work “IF” the DataGridView's property AllowUsersToAddRows is set to true . If it is set to false , then, the posted code is going to miss the last row in the grid.

In addition, depending on the grids DataSource , the data source itself may not allow new rows or be structured to add new rows. In this case, the AllowUsersToAddRows property becomes irrelevant, however in either case… the posted code will still miss the last row.

Since the code is technically correct “IF” the grid's AllowUsersToAddRows property is set to true . And, your question appears to be about the “missing” last row… I would assume that either the grids AllowUsersToAddRows property is set to false or the data source does not allow adding new rows.

To avoid this issue… I suggest an extra check for this “new” row in the row loop. If you check for the “new” row in the row loop, then it will not matter if the grids AllowUsersToAddRows property is true or false . Also using a foreach loop through the rows and cells may make things easier and may look something like…

foreach (DataGridViewRow row in dataGridView1.Rows) {
  if (!row.IsNewRow) {
    foreach (DataGridViewCell cell in row.Cells) {
      streamwriter.Write(cell.Value + "#");
    }
    streamwriter.WriteLine("");
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM