I have a method which writes a DataGridView into a text file:
private void textToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.FileName = DateTime.Now.ToString("yyyyMMddhhmm") + "_icmquery_" + GetTabName() + ".txt";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.OpenOrCreate))
{
switch (mainTabGroup.SelectedTab.Name.ToString())
{
case "findScriptsTab":
WriteTextFile(fs, findScriptsDataGrid);
break;
case "dialNumberAuditTab":
WriteTextFile(fs, findScriptsDataGrid);
break;
case "calltypeRequalificationTab":
WriteTextFile(fs, ctrDataGrid);
break;
case "targetAuditTab":
WriteTextFile(fs, targetAuditDataGrid);
break;
}
}
}
}
public void WriteTextFile(FileStream fs, DataGridView dataGrid)
{
using (TextWriter tw = new StreamWriter(fs))
{
foreach (DataGridViewRow row in dataGrid.Rows)
{
string line = string.Empty;
foreach (DataGridViewCell cell in row.Cells)
{
line = line + cell.Value + ",";
}
line = line.TrimEnd(',');
tw.WriteLine(line);
}
}
}
But instead of using the large switch statement in textToolStripMenuItem_Click() I would like to define a dictionary in my form. I have tried:
private Dictionary<TabPage, Func<FileStream, DataGridView>> WriteTextFileByTab(FileStream fs) = new Dictionary<TabPage, Func<FileStream, DataGridView>>()
{
{findScriptsTab, WriteTextFile(fs, findScriptsDataGrid)}
};
But visual studios won't even register this as a valid thing. I typed this in manually but none of the intense would fill anything in. When I hover over "findScriptsTab" it says its a field by used like a type, and WriteTextFile says the same thing. Any idea on how I could properly convert the switch statement to a dictionary so I can just say: WriteTextFileByTab[mainTabGroup.SelectedTab];?
You cannot define the parameter to the method for each item in the dictionary before you define the dictionary itself. You need to declare the parameter's identifier when constructing each value of the dictionary:
private Dictionary<TabPage, Func<FileStream, DataGridView>> WriteTextFileByTab
= new Dictionary<TabPage, Func<FileStream, DataGridView>>()
{
{findScriptsTab, fs => WriteTextFile(fs, findScriptsDataGrid)}
};
Of course if findScriptsTab and findScriptsDataGrid are instance fields, as I suspect that they are, you won't be able to use them when initializing another instance field. As such, you'll need to initialize this dictionary in the constructor, not when declaring it.
It also looks like the delegates in your dictionary (based on your implementation of WriteTextFile) don't actually need to return a DataGridView so the appropriate delegate to use is actually an Action<FileStream>, not a Func<FileStream, DataGridView>.
Related
I have to import data from a text file to a flat file database. I'm sure there's a faster way to load all the data into the database but I don't know how.
private void ImportButton_Click(object sender, EventArgs e)
{
string Path = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text File|*.txt";
ofd.ShowDialog();
if (ofd.FileName == string.Empty) return
Path = ofd.FileName;
string data;
using (var sr = new StreamReader(Path))
{
data = sr.ReadToEnd();
}
var items = data.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var count = 0;
foreach (var info in items.Select(ItemInfo.FromText).Where(info => info != null))
{
count++;
info.Index = ++Envir.ItemIndex;
Envir.ItemInfoList.Add(info);
}
MessageBox.Show(count + " Items have been imported");
UpdateInterface(true);
}
If you're doing this via C#, then I'd recommend SqlBulkCopy. I provided a similar answer to another question a while back. See that link for an example of how I've implemented it in the past.
If you want to know other options available to you then MSDN has quite a good list of options in their data loading guide; http://msdn.microsoft.com/en-us/library/dd425070(v=sql.100).aspx
Use OpenFileDialogwith EPPlus. I get a compile error of:
The name 'sheet' does not exist in the current context
Now, the obvious issue is how do I associate the selected Excel file with my EPPPlus & 2 what do I do to remove the error above?
using OfficeOpenXml;
using OfficeOpenXml.Drawing;
private void btn_ReadExcelToArray_Click(object sender, EventArgs e)
{
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\";
if (fd.ShowDialog() == DialogResult.OK)
{
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}
You are pretty close. All you have to do is create the package based on the stream (or you could use the fileinfo overload - either way). Like this:
var fd = new OpenFileDialog();
fd.Filter = "Excel Files|*.xlsx";
fd.InitialDirectory = #"C:\Temp\";
if (fd.ShowDialog() == DialogResult.OK)
{
using (var package = new ExcelPackage(fd.OpenFile()))
{
var sheet = package.Workbook.Worksheets.First();
var columnimport = sheet.Cells["A2:A"];
foreach (var cell in columnimport)
{
var column1CellValue = cell.GetValue<string>();
}
}
}
Try to do next - i want to check if some information is already exist if csv file, if yes - open form with label, and put to this label information from file
Code is next:
public void getEventTime(string filePath, string currDate, string currentDateTimeHM)
{
//reading the *.csv file and convert to the array of data
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
//create array for getting any vlaue from string
string[] arrOfData = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
sr.Close();
List<string> lines = new List<string>();
bool status=false;//variable for showing form if event exist
foreach (var l in arrOfData)
{
if (l.Contains(currDate) && l.Contains(currentDateTimeHM))
{
string[] temp = l.Split(',').Take(5).ToArray();
notLabel.Text = temp[1].ToString();
status = true;
}
}
if (status)
{
//show Notification Form
Form NotificationForm = new Notification();
NotificationForm.Visible = true;
}
}
all works perfect - if information exist - new form opens, but notLabel.Text = temp[0].ToString(); this part have return nothing. During debuging i got next
means that code is correct but in strange for me reason result in programm - without this text.
where I make some mistake?
Below form with label
checked
few rows from file NotificationDesigner.Form.cs
this.notLabel.AutoSize = true;
this.notLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.notLabel.Location = new System.Drawing.Point(12, 22);
this.notLabel.Name = "notLabel";
this.notLabel.Size = new System.Drawing.Size(34, 13);
this.notLabel.TabIndex = 0;
this.notLabel.Text = "label";
where do you call the method getEventTime and what is notLabel.
if the method getEventTime is called and set the notLabel.Text but after that the text is set again to string.Empty that there is the problem, so you should probably search or debug every change to notLabel.Text.
are you sure the it is notLabel the it is shown in the form? you can check that by registering to the mouseDown event and see that it is called when you click on the Label
one more thing, add break;
after your line
status = true;
go to the design and press the label, press F4 and search the name property, i bet it is not notLabel:
EDIT
i think i fount your problem
correct me if i'm wrong but this lines
if (status)
{
//show Notification Form
Form NotificationForm = new Notification();
NotificationForm.Visible = true;
}
are happening after you change the text... when what you meant is:
public void getEventTime(string filePath, string currDate, string currentDateTimeHM)
{
Form NotificationForm = new Notification();
//reading the *.csv file and convert to the array of data
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs);
//create array for getting any vlaue from string
string[] arrOfData = sr.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
sr.Close();
List<string> lines = new List<string>();
bool status=false;//variable for showing form if event exist
foreach (var l in arrOfData)
{
if (l.Contains(currDate) && l.Contains(currentDateTimeHM))
{
string[] temp = l.Split(',').Take(5).ToArray();
NotificationForm.NotText = temp[1].ToString();
status = true;
}
}
if (status)
{
//show Notification Form
NotificationForm.Visible = true;
}
}
and in the notification form do
public string NotText
{
set { notLabel.Text = value; }
}
I'm trying to match the indexes from "filename" and "filesize" with the ones from "xml". They contain filesize and names. I need to match them up in an if statment. I'm stuck though, and have no idea how to proceed.
public static void APB()
{
ArrayList filename = new ArrayList();
ArrayList filesize = new ArrayList();
var directory = new DirectoryInfo(Directory.GetCurrentDirectory());
var files= directory.GetFiles("*", SearchOption.AllDirectories);
long fnd = 0;
foreach (var file in files)
{
filename.Add(file.FullName);
filesize.Add(fnd += file.Length);
}
ArrayList xml = new ArrayList();
XmlTextReader reader = new XmlTextReader(dictonary.launcher);
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
xml.Add(reader.Name);
while (reader.MoveToNextAttribute())
xml.Add(reader.Name + "=" + reader.Value);
break;
}
}
}
Create anonymous types for each with the name and size and compare them.
How to save the ListView contents (including the ColumnHeaders) to a text file?
thanks.
There is nothing in .NET that will do this for you, you need to do the work yourself.
On whatever event will trigger your save: open the file, iterate through the list content writing the text to the file and then close the file. The close can of course be done via using:
using (var tw = new StreamWriter(filename)) {
foreach (ListViewItem item in listView.Items) {
tw.WriteLine(item.Text);
}
}
If you want to export all the subitems you must use this code:
StringBuilder sb;
if (listView.Items.Count > 0)
{
// the actual data
foreach (ListViewItem lvi in listView.Items)
{
sb = new StringBuilder();
foreach (ListViewItem.ListViewSubItem listViewSubItem in lvi.SubItems)
{
sb.Append(string.Format("{0}\t", listViewSubItem.Text));
}
sw.WriteLine(sb.ToString());
}
sw.WriteLine();
}
This should work 100%, I made this for a project of mine.
I know this is 4 years too late but here it is.
private void export2File(ListView lv, string splitter)
{
string filename = "";
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "SaveFileDialog Export2File";
sfd.Filter = "Text File (.txt) | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
filename = sfd.FileName.ToString();
if (filename != "")
{
using (StreamWriter sw = new StreamWriter(filename))
{
foreach (ListViewItem item in lv.Items)
{
sw.WriteLine("{0}{1}{2}", item.SubItems[0].Text, splitter, item.SubItems[1].Text);
}
}
}
}
}