C# DataGridView - Table is not populating - c#

I'm trying to display data that I pull from text files within my program.cs to a DataGridView, but the table remains blank when I run the code.
Another problem I have is that when the form opens it stops running through the code.
Basically what the code does is it downloads .zip files from an sftp server, unzips a text file, reads through the file adding each line to an array and splits a certain line into an array. I'm trying to get the variables from that array to appear on a DataGridView in my form.
Here is my code:
class Machine
{
public string MacNum { get; set; }
public string CashCount { get; set; }
public string VendCount { get; set; }
}
static class Program
{
[STAThread]
static void Main()
{
string zipTemp = (#"C:\Users\mark\Desktop\Project Dex\zipTemp\");
string machineCashCount = ("");
string hostIP = ("0.0.0.0");
string userName = ("UN");
string passWord = ("PW");
string remotePath = (#"/home/dex/RESPONSE/PROCESSED");
string localPath = (#"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
Application.Run(new Form1());
DataGridView dataGridView = new DataGridView();
IList<Machine> machines = new BindingList<Machine>();
dataGridView.DataSource = machines;
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = hostIP,
UserName = userName,
Password = passWord,
PortNumber = 22,
SshHostKeyFingerprint = "ssh-rsa 2048 96:48:96:52:8c:e7:de:c6:e1:00:08:7e:db:ad:e4:06"
};
using (Session session = new Session())
{
session.Open(sessionOptions);
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
session.GetFiles(remotePath, #"C:\Users\mark\Desktop\Project Dex\Temp\").Check();
}
DirectoryInfo directorySelected = new DirectoryInfo(#"C:\Users\mark\Desktop\Project Dex\Temp\PROCESSED\");
List<string> fileNames = new List<string>();
foreach (FileInfo fileInfo in directorySelected.GetFiles("*.zip"))
{
fileNames.Add(fileInfo.Name);
}
foreach (string fileName in fileNames)
{
string zipFilePath = localPath + fileName;
using (ZipFile zip1 = ZipFile.Read(zipFilePath))
{
var selection = (from e in zip1.Entries
where (e.FileName).StartsWith("01e")
select e);
Directory.CreateDirectory(zipTemp);
foreach (var e in selection)
{
e.Extract(zipTemp, ExtractExistingFileAction.OverwriteSilently);
}
}
DirectoryInfo dexDirect = new DirectoryInfo(#"C:\Users\mark\Desktop\Project Dex\zipTemp\");
List<string> dexName = new List<string>();
foreach (FileInfo dexInfo in dexDirect.GetFiles("*.dex"))
{
dexName.Add(dexInfo.Name);
}
foreach (string dexNames in dexName)
{
string dexFilePath = zipTemp + dexNames;
string[] lines = System.IO.File.ReadAllLines(dexFilePath);
foreach (string line in lines)
{
machineCashCount = Array.Find(lines,
element => element.StartsWith("VA1", StringComparison.Ordinal));
}
string[] MCC1 = machineCashCount.Split('*');
string[] nm = dexNames.Split('.');
int nam = int.Parse(nm[0], System.Globalization.NumberStyles.HexNumber);
// Console.WriteLine((nam + (":") + "Total cash count: ") + MCC1[1]);
// Console.WriteLine((nam + (":") + "Number of paid vends: ") + MCC1[2]);
Machine m = new Machine();
m.MacNum = nm[0];
m.CashCount = MCC1[1];
m.VendCount = MCC1[2];
machines.Add(m);
}
}
Application.Run(new Form1());
}
}
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}

1.Delete
Application.Run(new Form1());
DataGridView dataGridView = new DataGridView();
and
dataGridView.DataSource = machines;
2.At the end change
Application.Run(new Form1());
to
Application.Run(new Form1(machines));
3.Add constructor to Form1:
public Form1(IList<Machine> machines)
{
InitializeComponent();
dataGridView1.DataSource = machines;
}

What your program is basically doing is it runs the Form, downloads the zip file, processes the zip file and that's it.
You will need to do all this in the form's form_load event or a button click event instead of the Main().
remove the Application.Run(new form1) from the beginning of the code. Not required.
Move everything before the last Application.Run(new Form1) [Note this is with 'F' which is the correct one] to the a private function inside the form. Let's call it processFile()
Call this processFile() in the Form1_Load() event.
Assign m to the DataGridView's data property and call DataGridView.Bind() to bind the data to the datagrid control.
UPDATE:
Since you have a button and a Button_Click event, put the processFile() in the Button's click event. When the form is displayed, click the button to get the whole process running

Related

How to save files in specific locations without showing SaveDialog's Prompt

I'm been wondering is there a way to save a file in specific's folder in C#?
The only method that I know is 'SaveFileDialog' but the problems is I want to save files
in folder without showing saveFilesDialog's Box.
saveFilesDialog's Box : is a box that prompts you to Click 'YES' or 'CANCEL'.
Code samples
-In form1
public Form1()
{
InitializeComponent();
}
private string Path =#"D:\Files"; //locaction i wanna stores all the files in
private int i = 0;
private button1_Click(object sender,EventArgs e)
{
i++;
SaveDialogFile save = new SaveDialogFile();
if(Save.
if (save.ShowDialog() != DialogResult.OK)return; //Prompt's Dialog will show
save.Filter = "File Text(*.txt)|*.txt";
save.InitialDirectory = Path;
save.FileName = "txt"+i.ToString();
//Goal : i want 'save.FileName' store in 'Path' without Click 'OK' or Show Prompt Dialog's box
}
Expect Result
[1]: https://i.stack.imgur.com/9JqWO.png
Anyone can help me? I kinda stuck rn :)
This is my full code it's hard to read but you'll get the point
public partial class convertMp3ToWav : Form
{
public convertMp3ToWav()
{
InitializeComponent();
}
BackgroundWorker bw;
string withoutEx;
List<string> song_lists = new List<string>();
private void button1_Click(object sender, EventArgs e)
{
bw = new BackgroundWorker();
bw.DoWork += (obj, ae) => newThread();
bw.RunWorkerAsync();
}
void newThread()
{
Thread th = new Thread
((ThreadStart)(() =>
{
file();
}));
th.SetApartmentState(ApartmentState.STA);
th.Start();
th.Join();
}
void file()
{
string path = #"D:\musics\wav";
Directory.CreateDirectory(path);
FolderBrowserDialog f = new FolderBrowserDialog();
f.ShowDialog();
string[] lists = Directory.GetFiles(f.SelectedPath, "*.*", SearchOption.AllDirectories);
foreach (string list in lists)
{
if (Path.GetExtension(list) == ".mp3")
{
string fn = Path.GetFullPath(list);
withoutEx = Path.GetFileNameWithoutExtension(fn);
song_lists.Add(fn);
Console.WriteLine(withoutEx);
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Wav FIle (*.wav)|*.wav;";
//save.FileName = song_lists[0];
save.FileName = withoutEx;
save.InitialDirectory = path;
if (save.ShowDialog() == DialogResult.OK)
{
using (Mp3FileReader mp3 = new Mp3FileReader(fn))
{
using (WaveStream pcm = WaveFormatConversionStream.CreatePcmStream(mp3))
{
WaveFileWriter.CreateWaveFile(save.FileName, pcm);
}
}
}
}
}
}
}
this code's work pretty well!! but i need to click 'OK' everytime!!
so is there anyway to save file without click 'OK' everytime!!
Conceptually the only thing SaveFileDialog is doing, if you merely click OK when it shows, is changing the file extension*. Use Path.ChangeExtension instead
var pathToSaveWavTo = Path.ChangeExtension(pathToMp3, "wav");
The wav will be saved alongside the mp3. If you want to save it elsewhere, use Path.Combine to build a new path e.g.
pathToSaveWavTo = Path.Combine(#"c:\temp", Path.GetFileName(pathToSaveWavTo));
*I say this because giving it a filter of *.WAV and a filename xxx without the mp3 extension will cause it to give you a filename of xxx.wav when you only click OK, thus xxx.mp3 -> xxx.wav

Windows Form c# Reading and Writing to the same File on the same form Error?

I am currently trying to complete this c# windows form application. I am running into trouble.
Here is an image of my form...
The point of this form is too allow a user to input the data above. On the back end it should find the lowest test score, remove it from an array, and then when the user clicks "save student", the 3 lines of data ( The "Student Name", avg of 5 Test, and Letter grade based on the average ), should be saved to the students.txt file.
HOWEVER, my issue is can be seen in the list box below. My issue is that I am loading the data from the "students.txt" file ( using pre filled dummy data ), and I am getting an error each time I try to save the student ( because I cant read and write to the same file ) and the program will stop running.
Clicking on any of the pre filled data brings up another form with the data loaded into labels and that works just fine...
How can I stop this error so I can proceed with my work? I also am having trouble understanding the instructions where the data should be in a 2d array.
Here is an image of the instructions before I move on with my code. I am sure I can diverge from the instructions a bit.
Here is the code for my main Form...
namespace Tes3Part2
{
public partial class Form1 : Form
{
private List<PersonEntry> contactList = new List<PersonEntry>();
private List<string> contactListNames = new List<string>();
private InfromationForm personInfo = new InfromationForm();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
StreamReader inputFile = File.OpenText("students.txt");
while (!inputFile.EndOfStream)
{
PersonEntry person = new PersonEntry();
person.Name = inputFile.ReadLine();
person.AverageScore = inputFile.ReadLine();
person.LetterGrade = inputFile.ReadLine();
contactList.Add(person);
contactListNames.Add(person.Name);
}
contactListNames.Sort();
int x = 0;
while (x < contactListNames.Count)
{
contactList.Insert(x, contactList[SequentialSearch(contactList, contactListNames[x])]);
studentsListBox.Items.Add(contactList[x].Name);
x++;
}
}
catch
{
MessageBox.Show("Welcome.");
}
}
private int SequentialSearch(List<PersonEntry> inputList, string value)
{
bool found = false;
int index = 0;
int position = -1;
while (!found && index < inputList.Count)
{
if (inputList[index].Name == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
private void StudentsListBox_SelectedIndexChanged(object sender, EventArgs e)
{
personInfo.nameLabel.Text = contactList[studentsListBox.SelectedIndex].Name;
personInfo.scoreLabel.Text = contactList[studentsListBox.SelectedIndex].AverageScore;
personInfo.letterLabel.Text = contactList[studentsListBox.SelectedIndex].LetterGrade;
personInfo.ShowDialog();
}
private void Button1_Click(object sender, EventArgs e)
{
double test1 = (double.Parse(t1TestBox.Text));
double test2 = (double.Parse(t1TestBox.Text));
double test3 = (double.Parse(t1TestBox.Text));
double test4 = (double.Parse(t1TestBox.Text));
double test5 = (double.Parse(t1TestBox.Text));
double average = (test1 * test2 * test3 * test4 * test5) / 5;
// Declare a StreamWriter variable.
StreamWriter outputFile;
// Create a file and get a StreamWriter object.
outputFile = File.CreateText("students.txt");
// Write the info to the file.
outputFile.WriteLine(nameTextBox.Text);
outputFile.WriteLine(average);
outputFile.WriteLine("F");
outputFile.Close();
// Let the user know the name was written.
MessageBox.Show("The employee's name was added to the file EmployeePayroll.txt, located" +
"in the Debug File");
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
Here is the code for my Person Class
class PersonEntry
{
private string _name;
private string _average;
private string _letterGrade;
public PersonEntry()
{
_name = "";
_average = "";
_letterGrade = "";
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public string AverageScore
{
get { return _average; }
set { _average = value; }
}
public string LetterGrade
{
get { return _letterGrade; }
set { _letterGrade = value; }
}
}
Thank you in advance for all of your help!
As Steve mentioned you make use of the using statement while reading and writing to the file.
using (StreamReader inputFile = File.OpenText("students.txt"))
{
while (!inputFile.EndOfStream)
{
PersonEntry person = new PersonEntry();
person.Name = inputFile.ReadLine();
person.AverageScore = inputFile.ReadLine();
person.LetterGrade = inputFile.ReadLine();
}
}
using (StreamWriter outputFile = File.CreateText("students.txt"))
{
// Write the info to the file.
outputFile.WriteLine(nameTextBox.Text);
outputFile.WriteLine(average);
outputFile.WriteLine("F");
outputFile.Close();
}

System.Threading.ThreadStateException: how to solve it?

I have a Windows forms Application to open the file dialog, and then view xml files and xlsx files in a datagridview. I wrote the following code, Is my code OK or I need to do something more?
namespace MyFirstWindos
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
openFD.InitialDirectory = "C:";
openFD.Title = "Insert an File";
openFD.FileName = "";
openFD.Filter = "XML Files |*.xml| XLSX Files |*.xlsx ";
if (openFD.ShowDialog() == DialogResult.OK)
{
DataSet ds = new DataSet();
ds.ReadXml(openFD.FileName);
dataGridView1.DataSource = ds.Tables[0];
}
else
{
MessageBox.Show("Operation Cancelled");
}
}
}
}
namespace MyFirstWindos
{
public static class Program
{
public static void Main()
{
Compare_D_A d_A = new Compare_D_A();
d_A.CompareD_A();
// Compare_D_R d_R = new Compare_D_R();
// d_R.compareD_R();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
I have this exception
"System.Threading.ThreadStateException: 'The current thread must be set to single thread containment (STA) mode before OLE calls can be made. Make sure that the Main function is marked with STAThreadAttribute.
This exception is only activated if a troubleshooting program is linked to the process, at this row in my code if (openFD.ShowDialog() == DialogResult.OK).
How I can correct it and what it means?

C# Inputbox cancel button does not work

I have below code on my browse button.
How can I write code for inputbox cancel button.
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox(
"You are uploading File For SF NO. ", "Information", def, -1, -1);
ofd.ShowDialog();
ofd.Multiselect = true;
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = y.Substring(0, y.LastIndexOf("\\"));
String filename = y.Substring(y.LastIndexOf("\\"));
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
On Cancellation of InputBox, the return value is an empty string, so your code would be
if (sf_no!="")
{
//ok stuff here, including the showdialog logic as shown below
}
{
//cancel stuff here
}
Since ofd.ShowDialog can also be cancelled your code should be :
if (ofd.ShowDialog()==DialogResult.OK)
{
//do stuff on OK button
}
else
{
//do stuff on Cancel button
}
Either call ofd.Multiselect = true; before calling ShowDialog() or set it on Properties box if you'll always have Multiselect anyway.
Thus, your new code are now :
private void btnbrowse_Click(object sender, EventArgs e)
{
String sf_no = Microsoft.VisualBasic.Interaction.InputBox("You are uploading File For SF NO. ", "Information", def, -1, -1);
if (sf_no!="") //we got the sf_no
{
ofd.Multiselect = true;
if (ofd.ShowDialog()==DialogResult.OK)//user select file(s)
{
string[] result = ofd.FileNames;
foreach (string y in result)
{
String path = System.IO.Path.GetDirectoryName(y);
String filename = System.IO.Path.GetFileName(y);
string[] row = new string[] { sf_no,path, filename };
dataGridView2.Rows.Add(row);
}
}
else
{
//handle what happen if user click cancel while selecting file
}
}
else
{
//handle what happen if user click cancel while entering SF NO
}
}

How do I save the last folder selected by the user?

I have this and this only saves the last folder used when the user closes the application and re-opens it.
private void btnBrowse_Click(object sender, EventArgs e)
{
Properties.Settings.Default.Reload();
fbFolderBrowser.SelectedPath = AppVars.LastSelectedFolder;
if (fbFolderBrowser.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.LastSelectedFolder = fbFolderBrowser.SelectedPath.ToString();
Properties.Settings.Default.Save();
}
}
Every time the user selects a folder, I want to save that path. Then, when he clicks the browse button again, I want the default path to be his last selection.
The above is not working. It only saves the last path selected and goes back to it only if I restart the app. How would I go about saving the last path in the same app session?
You need to reload the settings:
Properties.Settings.Default.Reload();
Note that this only works when not running in Debug mode (AFAIK).
I'm gonna post my code here, because none of the answers I had seen addressed all the issues. This will save the location and re-load the settings for a file Browse dialog (file and folder browse dialogs are slightly different when getting path)... the answers above seem to be for the session only(?). Updated with new method to avoid config settings be lost with an update of clickonce app...
Code:
public class ConfigSettingsDictionary
{
public Dictionary<String, String> ConfigSettings = new Dictionary<String, String>();
}
ConfigSettingsDictionary MyConfigurationSettings = new ConfigSettingsDictionary();
private void SaveConfig()
{
using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
foreach (var pair in MyConfigurationSettings.ConfigSettings)
{
sw.WriteLine(pair.Key + "=" + pair.Value);
}
}
}
private void LoadConfig()
{
if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config"))
{
var settingdata = System.IO.File.ReadAllLines(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\YOUR_APP_NAME_PLUS_UNIQUE_VALUE.config");
for (var i = 0; i < settingdata.Length; i++)
{
var setting = settingdata[i];
var sidx = setting.IndexOf("=");
if (sidx >= 0)
{
var skey = setting.Substring(0, sidx);
var svalue = setting.Substring(sidx + 1);
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(skey))
{
MyConfigurationSettings.ConfigSettings.Add(skey, svalue);
}
}
}
}
}
private void UpdateConfig(Dictionary<String, String> keyvaluepairs)
{
foreach (var pair in keyvaluepairs)
{
if (!MyConfigurationSettings.ConfigSettings.ContainsKey(pair.Key))
{
MyConfigurationSettings.ConfigSettings.Add(pair.Key, pair.Value);
}
else
{
MyConfigurationSettings.ConfigSettings[pair.Key] = pair.Value;
}
}
}
then I use it like this (this saves the folder chosen in a file browse dialog and also the file chosen):
string lastused = "";
if (MyConfigurationSettings.ConfigSettings.ContainsKey("openFileDialog2_last_used"))
{
MyConfigurationSettings.ConfigSettings.TryGetValue("openFileDialog2_last_used", out lastused);
}
if (lastused != "")
{
openFileDialog2.InitialDirectory = lastused;
}
else
{
openFileDialog2.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
}
string filestring = "";
if (template_filename == "")
{
try
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
filestring = openFileDialog2.FileName;
String chosenPath = Path.GetDirectoryName(openFileDialog2.FileName);
Dictionary<String, String> settings_to_save = new Dictionary<String, String>();
settings_to_save.Add("openFileDialog2_last_used", chosenPath);
settings_to_save.Add("openFileDialog2_last_used_template_file", filestring);
UpdateConfig(settings_to_save);
}
else return;
}
catch (Exception ex)
{
MessageBox.Show("There was an error.", "Invalid File", MessageBoxButtons.OK);
return;
}
private void YOURFORMNAME_Load(object sender, EventArgs e)
{
// Load configuration file
LoadConfig();
}
private void YOURFORMNAME_FormClosing(object sender, FormClosingEventArgs e)
{
// Save configuration file
SaveConfig();
}

Categories

Resources