Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hello
It was never my intention tho use you solution what you made for me.
I have made a new question for my problem.
because I didn't get an answer from you to the old question.
So sorry again to you.
Regards
I don't know any other way tho tell you my apology.

My actual question is.
With the above code i can with a button the value from cel 1 2 and 4 write to a text file.
my question?
If the value in the rows 1 2 and 4 have already been written away.
And the next time the program starts again.
And the value in the rows 1 2 and 4 would be the same again if already written in the text file.
That this will not be written away again in the text file.
The program should then say entry already exist.

What I have tried:

you solotion to me!!

C#
using (TextWriter sw = File.AppendText(UitleenBestand))
                    {
                        foreach (DataGridViewRow row in dataGridView1.Rows)
                        {
                            object value = row.Cells[4].Value;
                            if (value is null || string.IsNullOrEmpty(Convert.ToString(value))) continue;

                            sw.Write(row.Cells[1].Value);
                            sw.Write('\t');
                            sw.Write(row.Cells[2].Value);
                            sw.Write('\t');
                            sw.Write(row.Cells[4].Value);
                            sw.WriteLine();
                        }
                    }
Posted
Updated 27-Nov-21 2:40am
v3
Comments
Maciej Los 26-Nov-21 13:54pm    
What's the question?
Greg Utas 26-Nov-21 18:48pm    
It appears to be a reference to one of his previous questions[^], where Richard contributed Solution 3.
[no name] 27-Nov-21 1:55am    
My actual question is.
With the above code i can with a button the value from cel 1 2 and 4 write to a text file.
my question?
If the value in the rows 1 2 and 4 have already been written away.
And the next time the program starts again.
And the value in the rows 1 2 and 4 would be the same again if already written in the text file.
That this will not be written away again in the text file.
The program should then say entry already exist.
Richard MacCutchan 27-Nov-21 5:12am    
You should use the Have a Question or Comment? or Reply link, to post a reply direct to Richard Deeming's answer at How save txt file if third column datagridview is empty[^].
#realJSOP 27-Nov-21 10:30am    
This guy ticked me off.

1 solution

One way to accomplish this is to read the existing file into a HashSet, and then attempt to add new entries to the HashSet.

The nature of a HashSet is to disallow duplicate values. Fortunately, when you try to add a duplicate entry, no exception is thrown, so there's no special handling necessary.

I wrote code to test this theory (took about 30 minutes), and it works fine.

This smells like a homework assignment (nobody in the real world enterprise environment would save a lot of data in a text file on the file system), so I'm not going to just hand over the actual code.

EDIT ====================================

I honestly don't believe you when you say this isn't a homework assignment, and think you should try to figure it out with just the hint I gave you. Truthfully, any hobby programmer worth his salt would have done that already. How else are you going to learn this stuff if you beg for code instead of researching and figuring it out on your own? You simply have to do the work.

C#
using System;
using System.Collections.Generic;
using System.IO;

namespace ConsoleApp4
{
	// This sample app creates several "rows" of data, and attempts to add them to
	// the text file. If column 4 is null/empty, the row will be ignored. Otherwise,
	// columns 1, 2, and 4 will be formatted into a single string and that string
	// will be added to the collection if the string is unique. If the string was
	// added to the collection, it will be appended to the text file.
	class Program
	{
		// the collection of unique entries
		private static HashSet<string> entries     = new HashSet<string>();
		// the filename to read/save data to
		private static string          fileName    = Path.Combine(Directory.GetCurrentDirectory(), "Test.txt");
		// a control to let the code know the data is being read from the file
		private static bool            loadingFile = false;

		static void Main(string[] args)
		{
			// read the existing data
			GetEntries();

			// i had to fake the data because I don't have a datagridview to work from
			DataGridViewRowList dataGridView1 = new DataGridViewRowList();

			// the string we'll be adding to the collection
			string entry = string.Empty;

			// iterate the data in the gridview
			foreach (DataGridViewRow row in dataGridView1.Rows)
			{
				// get column 4's data
				string value = row.Cells[4].Value as string;
				// if the string is not null/empty
				if (!string.IsNullOrEmpty(value))
				{
					// create a composite string
					entry = string.Format(@"{0}\t{1}\t{2}{3}",
											row.Cells[1].Value,
											row.Cells[2].Value,
											row.Cells[4].Value,
											Environment.NewLine);
					// and add it to the collection
					AddEntry(entry);
				}
			}

			// put a breakpoint on the following squiggly brace, and inspect the entries
			// collection. You should have 6 entries. When you run the program a 2nd
			// time, you should still only have 6 entries in the hashset.
		}

		/// <summary>
		/// Gets the current contents of the text file (if the file exists)
		/// </summary>
		static private void GetEntries()
		{
			// set a flag indicating that we're loding data. this is done to prevent the
			// app from trying to save the data we're reading from the file
			loadingFile = true;
			// if the file exists
			if (File.Exists(fileName))
			{
				// read each line
				foreach(string line in File.ReadLines(fileName))
				{
					// and add it to the collection
					AddEntry(line.Trim());
				}
			}
			// tell the app we're no longer loadingf data from the file
			loadingFile = false;
		}

		/// <summary>
		/// Add the specified string to the hashset
		/// </summary>
		/// <param name="entry"></param>
		static private void AddEntry(string entry)
		{
			// if the specified entry is succcessfully added to the collection
			if (entries.Add(entry))
			{
				// save the new entry to the file
				SaveEntry(entry); 
			}
		}

		/// <summary>
		/// If we're not loading data from the text file, append the specified entry 
		/// to the text file.
		/// </summary>
		/// <param name="value"></param>
		static private void SaveEntry(string value)
		{
			// if we're not loading from the file
			if (!loadingFile)
			{
				// save the specified entry to the file
				File.AppendAllText(fileName, value);
			}
		}
	}

	// my fake data (only useful in this sample application.
	/// <summary>
	/// represents a cell in a row
	/// </summary>
	public class DataCell
	{
		// make it an object so the cast in the main method makes sense
		public object Value { get; set; }
	}

	// represents a row in the gridview
	public class DataGridViewRow
	{
		// a list of cells in this row
		public List<DataCell> Cells { get; set; }
		// initialize the cells in this row
		public DataGridViewRow(string c0, string c1, string c2, string c3, string c4)
		{
			this.Cells = new List<DataCell>();
			this.Cells.Add(new DataCell() { Value = c0 });
			this.Cells.Add(new DataCell() { Value = c1 });
			this.Cells.Add(new DataCell() { Value = c2 });
			this.Cells.Add(new DataCell() { Value = c3 });
			this.Cells.Add(new DataCell() { Value = c4 });
		}
	}

	/// <summary>
	///  represents the gridview
	/// </summary>
	public class DataGridViewRowList : List<DataGridViewRow>
	{
		// collection of rows
		public DataGridViewRowList Rows { get { return this; } }

		public DataGridViewRowList()
		{
			// create our fake data, strarting with five valid unique rows
			this.Add(new DataGridViewRow("cell0", "cell1", "cell2", "cell3", "cell4"));
			this.Add(new DataGridViewRow("cell0A", "cell1A", "cell2A", "cell3A", "cell4A"));
			this.Add(new DataGridViewRow("cell0B", "cell1B", "cell2B", "cell3B", "cell4B"));
			this.Add(new DataGridViewRow("cell0C", "cell1C", "cell2C", "cell3C", "cell4C"));
			this.Add(new DataGridViewRow("cell0D", "cell1D", "cell2D", "cell3D", "cell4D"));
			// test null column 4 (this should not be added to the hashset)
			this.Add(new DataGridViewRow("cell0E", "cell1E", "cell2E", "cell3E", ""));
			// test duplicate row (this is a duplicate of the 5th row and should not be added to the hashset
			this.Add(new DataGridViewRow("cell0D", "cell1D", "cell2D", "cell3D", "cell4D"));
			// test almost duplicate row (this is a nearly duplicate row, and should be in the final hashset
			this.Add(new DataGridViewRow("cell0D", "cell1D", "cell2D", "cell3D", "cell4E"));
		}
	}
}
 
Share this answer
 
v3
Comments
[no name] 27-Nov-21 9:14am    
I am a hobby programmer and I use this program at home
what would you ask for the piece of code
#realJSOP 27-Nov-21 10:29am    
I updated my answer, but it annoys me that you couldn't work it out on your own. I abhor lazy beginners. You damn well better mark my solution as the answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900