-2

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.

Please find the table format here

            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

bowbow
  • 13
  • 4
  • 2
    "Text files should be in the format that it should start with the first line and end at last line." that's a weird format.. never saw such a file ;P – Mong Zhu Dec 14 '17 at 07:25
  • @mong zhu Please see the image first line and last line means the column value of the data grid view – bowbow Dec 14 '17 at 07:27
  • ok, do you know how to extract the values from the `DataGridView` ? do you know how to write a file? – Mong Zhu Dec 14 '17 at 07:27
  • I understood this point :) that was me trying to be funny ;) I guess I failed that one – Mong Zhu Dec 14 '17 at 07:28
  • @Mong zhu since I am beginner , I read about stream writer function , I can create a single file – bowbow Dec 14 '17 at 07:29
  • You would write one file after the other. Unless you have not time, then you can parallerlize it, but may be we should not start with that. Can you please post the code where you try to extract the values from the `DataGridView` ? and the code that you wrote to write the file? – Mong Zhu Dec 14 '17 at 07:32
  • I am currently using like this StreamWriter sW = new StreamWriter(MyDir+FileName); string lines = ""; for (int row = 0; row < Viewer.RowCount; row++) { for (int col = 0; col < Viewer.ColumnCount; col++) { lines = Viewer.Rows[row].Cells[col].Value.ToString(); } sW.WriteLine(lines); } sW.Close(); } – bowbow Dec 14 '17 at 07:34
  • @SivaVikas part of learning is `Doing` and in order for anyone to help you , you need to help yourself first, do some research, learn to code by googling for examples don't expect others to do the code for you. `This is not a Code it for me Site` – MethodMan Dec 14 '17 at 07:35
  • please post the additional information as an [edit](https://stackoverflow.com/posts/47807861/edit) into your post. You can format the code and it becomes readable. In comments it is a paint to read code. Thank you – Mong Zhu Dec 14 '17 at 07:36
  • @MethodMan I am doing , I have done lot to get me at this much. I searched lot . I just need help as i don't have much time , otherwise i can do with my own but it will take time. I will learn from this code also. – bowbow Dec 14 '17 at 07:45

2 Answers2

0

Below code breaks the DataGrid.DataSource Datatable into chunks that will go into each file.

private void SaveToFiles(DataTable srcData)
        {
            if (srcData.Rows.Count > 0)
            {
                int FileStart = 0;
                int FileEnd = -1;

                while (FileStart < srcData.Rows.Count)
                {
                    for (int row = FileStart; row < srcData.Rows.Count; row++)
                    {
                        if (string.IsNullOrEmpty(srcData.Rows[row].Field<string>(0)) == false)
                        {
                            FileStart = row;
                        }
                        if (string.IsNullOrEmpty(srcData.Rows[row].Field<string>(4)) == false)
                        {
                            FileEnd = row;
                            break;
                        }
                    }

                    var data = srcData.AsEnumerable().Skip(FileStart).Take(FileEnd - FileStart + 1);
                    SaveFile(data.ToList());
                    FileStart = FileEnd + 1;
                }
            }
        }

You need to add code to write the text to file in the format you wish - in place of the comment.

private void SaveFile(List<DataRow> fileData)
        {
            if (fileData != null && fileData.Count > 0)
            {
                string fileName = fileData[0].ItemArray[0].ToString();

                using (var fileStrm = File.Create(fileName + ".txt"))
                {
                    using (StreamWriter wrtr = new StreamWriter(fileStrm))
                    {
                       // handle writing to file here
                    }
                }
            }
        }
Prateek Shrivastava
  • 1,877
  • 1
  • 10
  • 17
  • not only for checking it should include first and last line – bowbow Dec 14 '17 at 07:31
  • Something Like this File: filename1.txt First Line BodyText1 Bodytext2 BodyText1 Bodytext2 BodyText1 Bodytext2 BodyText1 Bodytext2 BodyText1 Bodytext2 Last Line .. until you reach Last Line – bowbow Dec 14 '17 at 07:31
  • @SivaVikas - from your question - it isnt very clear what is it that you exactly want. we understand the grid data that you have. Please also show sample of the file that you want. i can then guide you. – Prateek Shrivastava Dec 14 '17 at 07:33
  • I need something like this 1stLine Bodytext1 BodyText2 Bodytext1 BodyText2 BodyText2 LastLine 1stLine Bodytext1 BodyText2 Bodytext1 BodyText2 Bodytext1 BodyText2 Bodytext1 BodyText2 Bodytext1 BodyText2 LastLine 1stLine Bodytext1 BodyText2 Bodytext1 BodyText2 Bodytext1 BodyText2 Bodytext1 BodyText2 LastLine – bowbow Dec 14 '17 at 07:38
  • @SivaVikas - Thats better. i will post the code answer soon. – Prateek Shrivastava Dec 14 '17 at 07:41
  • l`ll Check and let you know . Extremely thanks for you ease response.... – bowbow Dec 14 '17 at 09:36
0

Sometimes it helps to write the algorithm down in words. Imagine you would need to do it by hand. How would the recipe of actions look like? Here is one example:

1) you start walking down all rows that you have. (for-all rows)

2) IF you encounter a non-empty item in column 1, you know that this is your starting point and you remember that value.

3) now you know that at the very same row there is the 1stLine value in column with the index 1. You take and remember that value as well.

4) now at this point you can start with your BodyText collection of values. start at the same row that you are and walk down the rows. In each row you take the value from column 2 and 3 then you check in column 4. IF it is empty you put a \n and the end of your line and continue with the next row doing the step 4 again. ELSE it means that you have reached the LastLine and you can now write the content that you have remembered into a file.

5) Now you would clear the memory of the last file, take the next row and continue with step 2

Hope that helps you to solve your problem. IF you have questions, just ask in a comment. Good Luck

EDIT:

Ok with you code at hand let's see:

1) It is useless to check for the last line before you start the second loop. If you look at step 4) of my algorithm you need to gather first the values from column 3 and 4 and AFTER that you check for the column 4!

if (string.IsNullOrEmpty(DGV.Rows[fn].Cells[4].Value.ToString()) == false)
    break; // This will cancel the inner loop and you return to the outer loop 
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
  • Thanks Mong zhu, I ll try from your guidelines – bowbow Dec 14 '17 at 08:04
  • @SivaVikas you're welcome, just drop a comment if you get stuck – Mong Zhu Dec 14 '17 at 08:28
  • GridView1.Columns[Index].HeaderText; no prob got the syntax..:) – bowbow Dec 14 '17 at 09:41
  • You there i got stuck in the end – bowbow Dec 15 '17 at 11:47
  • so i have done that.. its creating multiple files... but i am unable to take last line condition into loop. last line will be always last row . i don`t know how make it....trying so far ... shal i post the code so far i hav done – bowbow Dec 15 '17 at 12:36
  • @bowbow jo, edit and post the code, then we can have a look on it :) – Mong Zhu Dec 15 '17 at 12:38
  • Have a look and give some suggestion – bowbow Dec 15 '17 at 12:42
  • @bowbow can you try to mark the steps from my algorithm with comments in your code 1) 2) and so on ?=! That would be helpful – Mong Zhu Dec 15 '17 at 12:47
  • Please check whether it is ok for you – bowbow Dec 15 '17 at 12:51
  • 1
    Thanks for your support mong.. i have done.. :) broke the loop in the correct place. – bowbow Dec 15 '17 at 13:06
  • is it possible to accept both as anser .. because both answers helped already tried to mark but didn`t work. – bowbow Dec 15 '17 at 13:41
  • @bowbow no that does not work, you have to choose. But you can upvote the other answer. As soon as you have enough reputation your vote will be counted and he/she will get the deserved reputation :) – Mong Zhu Dec 15 '17 at 13:43
  • Okay.. i don't enough reputation to do..i am having one more doubt.. could you help me out on this – bowbow Dec 19 '17 at 09:22
  • @bowbow Hi, what is bothering you ?=! :) – Mong Zhu Dec 19 '17 at 09:28
  • hi.. i have created application to generate multiple files from sql table .. after creation of those files... same sql table to be deleted.. i have checked..but no idea so far... give me some suggestion... to tackle it.... – bowbow Dec 19 '17 at 09:31
  • @bowbow what exactly is the problem? you don't know how to delete the table? – Mong Zhu Dec 19 '17 at 09:33
  • I know to delete the table.... actually its not a problem..... what I am doing for file generation ...1. I am creating a dummy SQL table.. 2. I am fetching same data to datagridview. 3. From DGView i generating files.... 4. After completion of the generation of files.... want to delete the same table.....(This feature i am going to add). have you got my point? – bowbow Dec 19 '17 at 09:37
  • "I know to delete the table" if you know, where is the problem? Make a button and delete the table. ?=! confused – Mong Zhu Dec 19 '17 at 09:39
  • its not a manual deletion... deletion need to be done automatically after the completion of files..ok leave it off ...no prob... – bowbow Dec 19 '17 at 09:57
  • @bowbow after you have created all the files, and you are sure that the data is save, just drop the table in the code. At the end of the code which creates the files. May be make an own method to do that – Mong Zhu Dec 19 '17 at 10:17