The code below works for me however, I would like to add a condition before it is added to the table. What I need is - if the "Scan Time" is between two dates, then it should be added to the "table" if not, then it should be disregarded.
This is for selecting the file..
private void btnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog()
{
Title = "Select the file to open.",
Filter = "DAT (*.dat)|*.dat|TXT (*.txt)|*.txt|All Files (*.*)|*.*",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
};
if (ofd.ShowDialog() == DialogResult.OK)
{
txtFilePath.Text = ofd.FileName;
loadDataToGridview();
}
}
This is for reading the file then adding it to the datagridview
private void loadDataToGridview()
{
DataTable table = new DataTable();
table.Columns.Add("Emp ID");
table.Columns.Add("Scan Time");
table.Columns.Add("Undefined 1");
table.Columns.Add("Undefined 2");
table.Columns.Add("Undefined 3");
table.Columns.Add("Undefined 4");
var lines = File.ReadAllLines(txtFilePath.Text).ToList();
lines.ForEach(line => table.Rows.Add(line.Split((char)9)));
return table;
}
I got the loadDataToGridview method from here but I do not know how to explode the
lines.ForEach(line => table.Rows.Add(line.Split((char)9)));
lambda expression to include the condition that I need. Let's assume that the name of the datepickers are dateFrom and dateTo. Your help is greatly appreciated.
Do not use ReadAllLines
method because it will load the entire file into memory. In other words, why load the entire file if only 1 line is between your dates.
Use the ReadLines
method instead. Why? See my answer here.
var lines = File.ReadLines("").Select(x => Split(x)).Where(x => IsBetweenDates(x[1]));
lines.ForEach(row => table.Rows.Add(row));
dataGridView1.DataSource = table;
You should add your own error handling here as per your needs. I have added a few for you:
private bool IsBetweenDates(string value)
{
var dateValue = DateTime.ParseExact(value, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
return dateValue >= fromDate.Value && dateValue <= toDate.Value;
}
private string[] Split(string line)
{
if (string.IsNullOrWhitespace(x))
{
// There is nothing in this line. Is this allowed in your case?
// If yes do whatever you need to do here. For example, log it or something.
}
var splits = line.Split((char)9);
if (splits.Length != 6)
{
// This line does not have 6 fields so what do you want to do?
}
return splits;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With