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
}
}
Related
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cmdAdd_Click(object sender, EventArgs e)
{
OpenFileDialog OP = new OpenFileDialog();
OP.Title = "Please select the wanted .exe";
string FileName = String.Empty;
string PathName = String.Empty;
OP.InitialDirectory = #"C:\Users\" + Environment.UserName.ToString() + #"\Desktop";
OP.DefaultExt = ".exe";
OP.Filter = "Game executable (*.exe) |*.exe";
DialogResult Ergebnis = OP.ShowDialog();
if (Ergebnis == DialogResult.OK)
{
FileInfo File = new FileInfo(OP.FileName);
if (File.Exists)
{
PathName = File.FullName;
}
}
if (PathName != String.Empty)
{
textBox1.Text = PathName;
listBox1.Items.Add(PathName);
}
}
private void cmdStart_Click(object sender, EventArgs e)
{
string SelectedItem = "";
if (listBox1.SelectedItem != null)
{
SelectedItem = listBox1.SelectedItem.ToString();
/*MessageBox.Show(SelectedItem);*/
}
Process Pro = new Process();
Pro.StartInfo.FileName = SelectedItem;
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
{
try
{
Pro.Start();
}
catch (Exception)
{
MessageBox.Show("The Start of the Program was aborted!\r\nOr you didn't specify the right Path!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
private void cmdSave_Click(object sender, EventArgs e)
{
StreamWriter SaveFile = new StreamWriter(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
foreach (var item in listBox1.Items)
{
SaveFile.WriteLine(item.ToString());
}
SaveFile.Close();
MessageBox.Show("EZPZ");
}
private void cmdLoad_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"C:\Users\" + Environment.UserName.ToString() + #"\Desktop\savedgames.txt");
string line = string.Empty;
try
{
line = sr.ReadLine();
while (line != null)
{
this.listBox1.Items.Add(line);
line = sr.ReadLine();
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
finally
{
sr.Close();
}
}
}
Hello Stackoverflow-Community,
So i've tried to be able to start the selected File(from the Listbox) by clicking the Start button.The items in the Listbox are loaded in from a .txt-File, But it seems that the path that i get (from the .txt-File) is not actually the same that was written inside.
For example: H:\Exe\556689600.exe is written inside the .txt-File but when i check while pausing the application the value of the SelectedItem is "H:(two backslashes)Exe(two backslashes)556689600.exe" so i'd like it to be H:\Exe\556689600.exe so it can be properly started.
EDIT: The main problem is that i can't start the .exe that i selected (via cmdStart) and i don't know why.
Please keep in mind that i'm (as you can see from the code) not very experienced in programming and that i'm not an native english speaker, so pardon me for any grammatical mistakes/logic mistakes made.
Thanks in advance,
Stephen
The problem is with:
DialogResult Ergebnis2 = MessageBox.Show("Would you like to start the Game right now?", "Game start?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (Ergebnis2.Equals(true))
DialogResult holds the Enum data 'DialogResult.Yes', so you need to compare it to that value, and not (true).
Edit:
I suggest practicing working with debug:
In this case, I plated a breakpoint on the 'cmdstart_Click' method and followed it step by step (Used F10)
I saw that we jump over the 'if' condition, and checked why.
it's my first question I'm asking here, so please be gentle with me ;)
So I've actually got two WinForms in my C# application I'm writing at the moment (I'm quite new to C#).
This window has a button, which saves photos from an usb device you selected before in a list box to another folder.
After clicking on this button my main thread is of course busy with copying, so I decided to create another WinForm which contains my ProgressBar.
Foreach completed copy, I want to increment my ProgressBar accordingly.
So I count the number of copies I have to do and give it the progressbar as maximum. But my problem at the moment is, that I really don't know how to increment the ProgressBar without getting a Thread Unsafe Exception.
Here's my ProgressWindow code:
public partial class ProgressWindow : Form
{
BackgroundWorker updateProgressBarThread = new BackgroundWorker();
private Boolean _isThreadRunning = false;
public Boolean IsThreadRunning
{
get { return _isThreadRunning; }
set { _isThreadRunning = value; }
}
private int _progressbarLength;
public int ProgressbarLength
{
get { return _progressbarLength; }
set { _progressbarLength = value; }
}
private int progress = 1;
public ProgressWindow()
{
Show();
InitializeComponent();
}
private void StartUpdateThread(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
// Reports progress to the ProgressChangedEvent function. (Thread Safe)
}
private void FinishProgressThread(object sender, RunWorkerCompletedEventArgs e)
{
if (!_isThreadRunning)
{
MessageBox.Show("Erfolgreich kopiert");
Close();
}
}
private void ProgressChangedEvent(object sender, ProgressChangedEventArgs e)
{
this.copyProgressbar.Value = e.ProgressPercentage;
this.progressStatus.Text = e.ProgressPercentage.ToString();
}
public void CallUpdateThread()
{
updateProgressBarThread.WorkerReportsProgress = true;
updateProgressBarThread.DoWork += new DoWorkEventHandler(StartUpdateThread);
updateProgressBarThread.ProgressChanged += new ProgressChangedEventHandler(ProgressChangedEvent);
updateProgressBarThread.RunWorkerCompleted += new RunWorkerCompletedEventHandler(FinishProgressThread);
updateProgressBarThread.RunWorkerAsync();
}
}
I want to increment my ProgressBar with 1 after each succesful copy.
How do I do this from my main thread?
This is the function which actually handles the copy process
private void SaveFile(System.IO.DirectoryInfo root)
{
try
{
IEnumerable<DirectoryInfo> directoriesNames = root.EnumerateDirectories();
// New instance of thread ProgressWindow.
ProgressWindow progress = new ProgressWindow();
progress.CallUpdateThread();
foreach (DirectoryInfo element in directoriesNames)
{
// Query all subdirectories and count everything with the in the configuration made settings.
if (!element.Attributes.ToString().Contains("System"))
{
// Now we insert the configuration we applied.
String fileExtension = null;
if (Properties.Settings.Default._configPhoto)
{
fileExtension = "*.jpg";
}
if (Properties.Settings.Default._configWordDocument)
{
fileExtension = "*.odt";
}
FileInfo[] jpgList = element.GetFiles(fileExtension, SearchOption.AllDirectories);
// set the size of the progress bar
progress.ProgressbarLength = jpgList.Count();
// Now we go through all our results and save them to our backup folder.
foreach (FileInfo tmp in jpgList)
{
string sourceFilePath = tmp.FullName;
string destFilePath = PATHTOBACKUP + "\\" + tmp.Name;
progress.IsThreadRunning = true;
try
{
System.IO.File.Copy(sourceFilePath, destFilePath, true);
}
catch (IOException ioe)
{
MessageBox.Show(ioe.Message);
}
}
}
}
// progress.IsThreadRunning = false;
}
catch (UnauthorizedAccessException e)
{
MessageBox.Show(e.Message);
}
}
It's pretty obvious that I have to do this after this function
System.IO.File.Copy(sourceFilePath, destFilePath, true);
But how do I report this to my ProgressWindow?
I really hope I explained it well enough, not sure if I'm missing something important.
Thanks in advance guys
Here is a compact example of the key components:
Clicking button starts new thread worker
Progress is done by file lengths, not by number of files
BeginInvoke used to update the progress bar (avoid cross Thread exception)
ProgressBar pb = new ProgressBar() { Minimum = 0, Maximum = 100 };
Button btn = new Button();
btn.Click += delegate {
Thread t = new Thread(() => {
DirectoryInfo dir = new DirectoryInfo("C:\\temp\\");
var files = dir.GetFiles("*.txt");
long totalLength = files.Sum(f => f.Length);
long length = 0;
foreach (var f in files) {
length += f.Length;
int percent = (int) Math.Round(100.0 * length / totalLength);
pb.BeginInvoke((Action) delegate {
pb.Value = percent;
});
File.Copy(f.FullName, "...");
}
});
t.IsBackground = true;
t.Start();
};
I'm very new to C#. I'm populating a File Explorer using C#. What i want to do now is implementing the listView1_MouseDoubleClick() method so that when I double-click in a sub folder, the current listView will be cleared then it will display files and folders in that subfolders (like what Windows Explorer does). Here's my code:
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
string path = listView1.Items[i].Name;
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
private void LoadFilesAndDir(string address)
{
DirectoryInfo di = new DirectoryInfo(address);
try
{
foreach (FileInfo fi in di.GetFiles())
{
listView1.Items.Add(fi.Name);
}
try
{
foreach (DirectoryInfo listd in di.GetDirectories())
{
listView1.Items.Add(listd.FullName, listd.Name, 0);
}
}
catch (Exception e1)
{
}
}
catch (Exception e1)
{
}
}
But it failed to run. When I debug this error step by step, I found out that after this statement: path = listView1.Items[i].Name; the path variable's value is "". So i guess that the reason which let to the error. But I don't know how to fix that... Could you guys help me with this ? Thanks a lot in advanced !
Make sure that you declare the string 'path' first
string path = "";
Then insert this code:
private void listView1_MouseDoubleClick(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
path = Convert.ToString(listView1.Items[i]);
// This replaces the part "List View Item: {"
path = path.Replace("ListViewItem: {", "");
// This replaces the part "}"
path = path.Replace("}", "");
comboBox1.Text = path;
listView1.Items.Clear();
LoadFilesAndDir(path);
}
}
}
The code is a bit long, but it works!
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();
}
I want to put a test loop on the button click event. When I click this button, it reads the contents of the text file, but I want it to pop up an error message showing “unable to read file”, if it’s not a text file....
This is my code
private void button3_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
richTextBox1.Text = sr.ReadToEnd();
sr.Close();
}
How can I go about it?
A few if-statements and the namespace System.IO will do it
string filename = textBox1.Text;
if (Path.GetExtension(filename).ToLower()) == ".txt") {
if (File.Exists(filename)) {
// Process the file here
} else {
MessageBox.Show("The file does not exist");
}
} else {
MessageBox.Show("Not a text file");
}
Not the best code, but it should work. Ideally you would separate the logic into two methods, a function to check the file exists and is a text file (returning a bool), another to read the contents if the check function returned true and populate the textbox with the contents.
EDIT: This is better:
private void button3_Click(object sender, EventArgs e)
{
string filePath = textBox1.Text;
bool FileValid = ValidateFile(filePath);
if (!IsFileValid)
{
MessageBox.Show(string.Format("File {0} does not exist or is not a text file", filePath));
}
else
{
textbox2.Text = GetFileContents(filePath);
}
}
private bool IsFileValid(string filePath)
{
bool IsValid = true;
if (!File.Exists(filePath))
{
IsValid = false;
}
else if (Path.GetExtension(filePath).ToLower() != ".txt")
{
IsValid = false;
}
return IsValid;
}
private string GetFileContents(string filePath)
{
string fileContent = string.Empty;
using (StreamReader reader = new StreamReader(filePath))
{
fileContent = reader.ReadToEnd();
}
return fileContent;
}