如何不在StreamWriter中打印最后一个分隔符?

时间:2014-01-14 17:02:51

标签: c# datagridview character streamwriter

我想删除最后一个字符“|”从每一行。我不希望最后一列用该字符关闭。你能帮忙吗?

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 个答案:

答案 0 :(得分:2)

请尝试dataGridView1.Columns.Count - 1

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

这样,它就不会在该行的最后一个元素之后打印|,即y == dataGridView1.Columns.Count - 1

或者,像@DaveZych提到的那样,你可以使用string.Join来避免检查迭代器并以这样的结尾结束,

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

sw.Close();

答案 1 :(得分:1)

您应该针对y

检查count,而不是count - 1
if (y != dataGridView1.Columns.Count - 1)
{
     sw.Write("|");                    
}

您从y < count循环,这意味着y永远不会等于count

或者,您可以在整行上使用string.Join

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);
}

这将创建一个字符串,其中包含由|分隔的所有值。

答案 2 :(得分:0)

您正在丢失代码的最后一行,因为您使用“&lt;”和“伯爵-1”。这是使用“|”执行所需的工作代码并且不会丢失最后一行:

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();
}

}