so everytime this runs through
OpenFileDialog xmlOpenFileDialog = new OpenFileDialog();
xmlOpenFileDialog.Filter = #"XML|*.xml";
xmlOpenFileDialog.FilterIndex = 1;
//Start
//Implement a way for user to have last opened file shown if program is closed by accident?
//xmlOpenFileDialog.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//End
xmlOpenFileDialog.Multiselect = false;
DialogResult userClickedOk = xmlOpenFileDialog.ShowDialog();
if (userClickedOk == DialogResult.OK)
{
lastKnownFileName = xmlOpenFileDialog.FileName;
System.IO.Stream filestream = xmlOpenFileDialog.OpenFile();
using (System.IO.StreamReader reader = new StreamReader(filestream))
{
UpChart_Chart.Serializer.IsResetWhenLoading = false;
UpChart_Chart.Serializer.Content = SerializationContents.Data;
UpChart_Chart.Serializer.SerializableContent += ",DataPoint.AxisLabel,DataPoint.Label,Series.AxisLabels,Series.Name,Series.ChartType,ChartChartArea.Name";
UpChart_Chart.Serializer.Load(reader);
}
then the data we have in the chart resets when new inputs happens?
how do we make sure that the data we have is correctly put in the right areas?
Related
I use the OpenFileDialog in my WPF program to give the user the option to select a .csv file and read it into the program. Now I have the path and everything from the file that the user wants and now I want to add 2 more cells to the Excel file after a button click. How should I change it so that as soon as the button is pressed, 2 columns and cells are added to the previously imported Excel file. Here is my OpenFileDialog how I get the file OpenFileDialog::
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
openFileDialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openFileDialog.Title = "CVS Datei Auswählen zum Konvertieren";
if (openFileDialog.ShowDialog() == true)
{
foreach (string filename in openFileDialog.FileNames)
{
tbxFiles.Items.Add(System.IO.Path.GetFileName(filename));
string temp;
var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
temp = streamReader.ReadToEnd();
test = temp;
}
}
}
SaveFileDialog:
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "CVS (*.cvs)|*.csv|All files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
List<String> liste = new List<String>();
// test = test + "Hallo;";
//File.WriteAllText(dialog.FileName, test);
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader(test);
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{""},{""}";
}
counter++;
}
file.Close();
}
In my "test" string I have now read in what is in the cvs file via streamreader. This is what the cvs Header looks like:
Picture 1
and so how i want it look like after my C# change:
Picture2
tbxFiles = my TextBox where the path of the selected file is shown.
So how can I add additional Excel columns with associated cells to the imported Excel file in Code Behind 2?
There you go:
....
while ((line = file.ReadLine()) != null)
{
if (counter == 0)
{
line += ",column1,column2";
}
else
{
line += $",{value1},{value2}";
}
counter++;
}
...
I'm trying to open a file but I want it filter out to only .dat file.
using (OpenFileDialog fileChooser = new OpenFileDialog())
{
result = fileChooser.ShowDialog();
fileName = fileChooser.FileName; //Get file name.
fileChooser.Filter = "Data File|*.dat;";
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
}
When having a OpenFileDialog in "using" the filter, defaultExt and Addextension doesn't work.
You should set filters before the call of "ShowDialog" method.
This should work.
using (var fileChooser = new OpenFileDialog())
{
// define the filters (first description | first filter; second description ...
fileChooser.Filter = "Data File|*.dat";
// select the first filter
fileChooser.FilterIndex = 1;
fileChooser.DefaultExt = "dat";
fileChooser.AddExtension = true;
// show the Opendialog
if (fileChooser.ShowDialog() == DialogResult.OK)
{
// get the path of specified file
var filename = fileChooser.FileName;
// use the filename to open the file...
}
}
I have been working on converting a GUI script from another language to C# using VS2017. I have the whole thing working for the most part, but have come on a problem. The gui has a listview which I am populating either manually through entering data in various fields or as an import from a CSV. The manual entry works just fine. The CSV import works as well, however it is pulling the header line into the listview. Here is the code I am using for the button to kick off the import:
private void import(object sender, RoutedEventArgs e)
{
OpenFileDialog xls = new OpenFileDialog();
xls.Multiselect = false;
xls.Filter = "CSV files (*.csv)|*.csv";
xls.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
xls.ShowDialog();
string ins;
if (xls.FileName != null)
{
FileStream srcFS;
srcFS = new FileStream(xls.FileName, FileMode.Open);
StreamReader srcSR = new StreamReader(srcFS, System.Text.Encoding.Default);
do
{
ins = srcSR.ReadLine();
if (ins != null)
{
string[] parts = ins.Split(',');
MyItems.Add(new MyItem
{
Name = parts[0],
CPU = parts[1],
RAM = parts[2],
IP = parts[3],
Subnet = parts[4],
PortGroup = parts[5],
Gateway = parts[6],
DNS = parts[7],
Description = parts[8],
Template = parts[9],
Host = parts[10],
Site = parts[11],
Folder = parts[12],
Datastore = parts[13],
Patch = parts[14],
HDD1_Size = parts[15],
HDD2_Size = parts[16],
HDD3_Size = parts[17],
HDD4_Size = parts[18],
HDD5_Size = parts[19],
HDD6_Size = parts[20],
HDD7_Size = parts[21],
HDD8_Size = parts[22],
HDD9_Size = parts[23],
HDD10_Size = parts[24]
});
}
} while (ins != null);
srcSR.Close();
}
}
I have been googling for some ways to skip the first line, but it most of the suggestions have been to iterate through line by line and write the lines one at a time, which slows the import process (there could be hundreds of lines). Just curious if there is a simple way to tell the StreamReader where to begin reading the file.
You want to read a line and throw it away. Just add an ins = srcSR.ReadLine(); right above your do.
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 want to load content stored in a file, into the fields of a WinForms GUI.
My approach right now: I've got a streamwriter which writes each text box to a line in a .txt file. I have the streamreader setup but i have no idea how to get it to load each line into seperate text boxes. For example: Task1_name (line 1) and task1_desc (line 2) need to be in seperate text boxes, how could i get it to load into the boxes?
Thanks
Code:
Save Button:
void Save_buttonClick(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you want to save?", "Save", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
sw.WriteLine(task1_name.Text);
sw.WriteLine(task1_desc.Text);
sw.WriteLine(task1_date.Value);
sw.WriteLine(task1_check.Checked);
sw.Close();
}
}
Load Button:
void Load_buttonClick(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Do you want to load?", "Load", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamReader sr = new StreamReader(file);
sr.Close();
}
}
Use XML Serialization. It would look something like this:
public class MySettings
{
public String name {get;set;}
public String name {get;set;}
public DateTime date {get;set;}
public bool checked {get;set;}
}
void Save()
{
var s = new MySettings
{
name = this.task1_Name.Text,
desc = this.task1_Desc.Text,
date = this.task1_Date.Value,
checked = this.task1_Check.Checked
};
var ser = new XmlSerializer(typeof(MySettings));
using (var fs = new FileStream(path, FileMode.Create))
{
using (var tw = new StreamWriter(fs, new UTF8Encoding()))
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "");
ser.Serialize(tw, this, ns);
}
}
}
And to load it would look like this:
static MySettings Load()
{
var ser = new XmlSerializer(typeof(MySettings));
MySettings settings = null;
try
{
using (var s = File.OpenRead(path))
{
settings = (MySettings) ser.Deserialize(s);
// optionally validate here
}
}
catch (Exception ex1)
{
MessageBox.Show("Cannot read settings. " + ex1.Message,
"error");
settings = null;
}
return settings;
}
And then of course resetting your form would be like this:
var settings = Load();
this.task1_Name.Text = settings.name;
this.task1_Desc.Text = settings.desc;
this.task1_Date.Value = settings.date;
this.task1_Check.Checked = settings.checked;
You can add every line into a List and access them by index:
//...
List<string> lines = new List<string>();
using (StreamReader sr = new StreamReader(file))
{
while(!sr.EndOfStream)
{
lines.Add(sr.ReadLine());
}
}
task1_name.Text = lines[0];
task1_desc.Text = lines[1];
//...
Just read the lines and populate the form in the same order as you wrote them:
if (dialogResult == DialogResult.Yes)
{
FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamReader sr = new StreamReader(file);
task1_name.Text = sr.ReadLine();
task1_desc.Text = sr.ReadLine();
task1_date.Value = DateTime.Parse(sr.ReadLine());
task1_checked.Checked = bool.Parse(sr.ReadLine());
sr.Close();
}