Search code examples
c#datagridviewrowscells

How to add simple text between columns in datagridview output? C#


I am trying to convert datagridview to text file. So when i am using this code i am getting that text output. Ex.

"Start of the text! This 170 is number This 80 is number End of the text!"

This 170 and 80 numbers are generating from datagridview.

I want to get that output. Ex.

"Start of the text! This 170 is number 80 End of the text!"

So i dont want to add "This " and " is number" on second column.

Sorry for my bad English if this text is not understoodable.

private void button3_Click(object sender, EventArgs e)
    {
        TextWriter writer = new StreamWriter(@"C:\Users\ESTIT09\Desktop\test.txt");
        for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
        {
            writer.WriteLine("Start of the text!");
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                writer.Write("This " + dataGridView1.Rows[i].Cells[j].Value.ToString() + " is number" + "\r\n");
            }

            writer.WriteLine("End of the text!");
        }
        writer.WriteLine("end sub");
        writer.Close();
    }

Solution

  • This should work. Replace your for loop with this block.

        for (int j = 0; j < dataGridView1.Columns.Count; j++)
                    {
                        if(j==0) //change the index (0 or 1)for what you are looking for
                        {
                             writer.Write("This " + dataGridView1.Rows[i].Cells[j].Value.ToString() + " is number" + "\r\n");
                        }
                        else
                        {
                            writer.Write(dataGridView1.Rows[i].Cells[j].Value.ToString() + "\r\n");     
                        } 
                    }