Вопрос

I want to remove last character "|" from each row. I dont want to have last column closed with that character. Can you help?

private void spremiUDatotekuToolStripMenuItem1_Click(object sender, EventArgs e)
{
    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        System.IO.StreamWriter sw = new
        System.IO.StreamWriter(saveFileDialog1.FileName);

        for (int x = 0; x < dataGridView1.Rows.Count - 1; x++)
        {

            for (int y = 0; y < dataGridView1.Columns.Count; y++)
            {
                sw.Write(dataGridView1.Rows[x].Cells[y].Value);
                if (y != dataGridView1.Columns.Count)
                {
                    sw.Write("|");                    
                }
            }
            sw.WriteLine();
        }
        sw.Close();
    }
}
Это было полезно?

Решение 3

You are losing the last row from the code because you use "<" and "Count-1". This is the working code that also does what you want with the "|" and does not lose the last row:

private void spremiUDatotekuToolStripMenuItem1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    System.IO.StreamWriter sw = new
    System.IO.StreamWriter(saveFileDialog1.FileName);

    for (int x = 0; x < dataGridView1.Rows.Count; x++)
    {

        for (int y = 0; y < dataGridView1.Columns.Count; y++)
        {
            sw.Write(dataGridView1.Rows[x].Cells[y].Value);
            if (y != dataGridView1.Columns.Count - 1) // Count - 1 is the last value. y will never reach count because you have "<" sign
            {
                sw.Write("|");                    
            }
        }
        sw.WriteLine();
    }
    sw.Close();
}

}

Другие советы

Try dataGridView1.Columns.Count - 1 instead,

if (y != dataGridView1.Columns.Count - 1)
{
    sw.Write("|");                    
}

That way it won't print | after the last element on that row, which is when y == dataGridView1.Columns.Count - 1.

Alternatively, like @DaveZych mentions, you could user string.Join to avoid checking iterators and end with something like this,

foreach (var row in dataGridView1.Rows)
{
    var rowValue = string.Join("|", row.Cells.Select(cell => cell.Value));
    sw.Write(rowValue);    
}

sw.Close();

Instead of checking y against the count, you should check it against count - 1

if (y != dataGridView1.Columns.Count - 1)
{
     sw.Write("|");                    
}

You're looping from y < count which means that y will never be equal to count.

Alternatively, you could use string.Join on the entire row:

for (int x = 0; x < dataGridView1.Rows.Count - 1; x++)
{
    string line = string.Join("|", dataGridView1.Rows[x].Cells.Select(c => c.Value);
    sw.WriteLine(line);
}

This will create a string with all values delimited by |.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top