Hi all I am having the following results in my data grid view, I want to print these data to multiple text files.
Text files should be in the format that it should start with 1stLine
(Column Value Please see the image) and end at LastLine
(Column Value Please see the image).
consider filename1 column value as the filename of that file.
likewise, I want to create multiples files. I am not sure to create multiple files based on the range.
private void Create_Click(object sender, EventArgs e)
{
int FileStart = 0;
int FileEnd = 0;
string FileName = "";
String MyDir = "C:\\Test\\";
StringBuilder builder = new StringBuilder();
int rowcount = DGV.Rows.Count;
int columncount = DGV.Columns.Count;
for (int fn = 0; fn < rowcount - 1; fn++)// fro running down all rows
{
if (string.IsNullOrEmpty(DGV.Rows[fn].Cells[0].Value.ToString()) == false) //checking for the filename
{
FileName = DGV.Rows[fn].Cells[0].Value.ToString();
builder.Clear();
FileStart = fn;
if (string.IsNullOrEmpty(DGV.Rows[fn].Cells[4].Value.ToString()) == false) // this is where i tried to check the last line
{
for (int row = fn; row < rowcount - 1; row++)
{
FileEnd = row;
}
}
for (int i = FileStart; i < rowcount - 1; i++) // here start generating the file based on first and last line .. but as of now i took rowcount as last line.. if i put last line returns nothing...i know this is where i am wrong, but i tried lot of options
{
List<string> cols = new List<string>();
for (int j = 1; j < columncount; j++)
{
cols.Add(DGV.Rows[i].Cells[j].Value.ToString());
}
builder.AppendLine(string.Join("\n", cols.ToArray()));
if (!Directory.Exists(MyDir))
{
Directory.CreateDirectory(MyDir);
}
System.IO.File.WriteAllText(MyDir + FileName, builder.ToString());
MessageBox.Show(@"Text file was created.");
}
}
else
{
fn = fn + 1;
}
}
}
Need output file like
Filename1
1stLine Bodytext1 BodyText2
Bodytext1 BodyText2
BodyText2 LastLine
Filename2
1stLine Bodytext1 BodyText2
Bodytext1 BodyText2
Bodytext1 BodyText2
Bodytext1 BodyText2
Bodytext1 BodyText2 LastLine
Filename3
1stLine Bodytext1 BodyText2
Bodytext1 BodyText2
Bodytext1 BodyText2
Bodytext1 BodyText2 LastLine