How do I fix the speech synthesizer repeating itself c#? - c#

So basically I used two speech recognition engines(speechrecog & speechrecog1) and one speech synthesizer. When the speechrecog is asked a question like how are you
it then replies I am fine (if the computer picks 2 from the two numbers 1,2). Then it initializes the second speech recognition engine. When it does its stuff. It then turns the second one off and the first one on again. But the problem is when using the second speech recognition engine it repeats( speech synthesizer) the number of times I have tried the second speech recognition engine out.
Here's my code for that form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
namespace Project_Juliet
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}
class FullScreen
{
public void EnterFullScreenMode(Form targetForm)
{
targetForm.WindowState = FormWindowState.Normal;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;
}
public void LeaveFullScreenMode(Form targetForm)
{
targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
targetForm.WindowState = FormWindowState.Normal;
}
}
// System.Globalization.CultureInfo cl2 = new System.Globalization.CultureInfo("en-US");
SpeechRecognitionEngine speechrecog = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
SpeechSynthesizer ss = new SpeechSynthesizer();
PromptBuilder pb = new PromptBuilder();
Choices zlist = new Choices();
Form2 frm = new Form2();
FullScreen fs = new FullScreen();
bool SpeechRecognitionState = true;
Choices dirlist = new Choices();
SpeechRecognitionEngine speechrecog1 = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
bool sprs2 = false;
Choices us = new Choices();
string dir234;
string[] gm;
private void Form11_Load(object sender, EventArgs e)
{
listBox1.Visible = false;
string dir = "C:/Users/" + Environment.UserName + "/Documents/Juliet/response";
DirectoryInfo dinfo = new DirectoryInfo(dir);
FileInfo[] Files = dinfo.GetFiles("*.txt");
webBrowser1.ScriptErrorsSuppressed = true;
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
listBox1.Items.Add(file2.Name.Replace(yts + "", ""));
}
/* String[] list = new String();
list = listBox1.Items.OfType<string>().ToList();
*/
fs.EnterFullScreenMode(this);
textBox1.Width = toolStrip1.Width - 10;
// toolStripTextBox1.Width = toolStrip1.Width - 30;
// toolStripTextBox1.Select();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Teen);
zlist.Add(new string[] { "exit"});
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
dirlist.Add(new string[]{"Mr.Danely"});
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
dirlist.Add(file2.Name.Replace(yts + "", ""));
}
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
try
{
if (SpeechRecognitionState == true)
{
speechrecog.RequestRecognizerUpdate();
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
speechrecog.SpeechRecognized += speechrecog_SpeechRecognized;
speechrecog.SetInputToDefaultAudioDevice();
speechrecog.RecognizeAsync(RecognizeMode.Multiple);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
//us.Add(new string[] { "yes","no","good","bad" });
us.Add(new string[] { "exit" });
Grammar gr12 = new Grammar(new GrammarBuilder(us));
if (sprs2 == true)
{
}
}
void speechrecog1_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if(File.Exists(#"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//"+e.Result.Text.ToString()+".txt"))
{
string hjjk = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//" + e.Result.Text.ToString() + ".txt";
StreamReader file = new StreamReader(hjjk);
string readText = file.ReadLine();
file.Close();
ss.Speak(readText);
timer2.Interval = 10;
timer2.Start();
}
}
void speechrecog_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string igput = e.Result.Text.ToString();
dir234 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//" + igput + ".txt";
if (igput == "exit")
{
speechrecog.RecognizeAsyncStop();
this.Hide();
frm.Closed += (s, args) => this.Close();
frm.Show();
}
else
{
if (File.Exists(dir234))
{
StreamReader file = new StreamReader(dir234);
string readText = file.ReadLine();
file.Close();
if (readText.Contains("%"))
{
string[] words = readText.Split('%');
Random r = new Random();
int selection = r.Next(1, 3);
if (selection == 1)
{
ss.SpeakAsync(words[0]);
}
if (selection == 2)
{
if (readText.Contains('#'))
{
SpeechRecognitionState = false;
us.Add(new string[] { "exit" });
gm = words[1].Split('#');
string speak = words[0] + gm[0];
ss.SpeakAsync(speak);
List<string> lk = gm.ToList();
lk.RemoveAt(0);
string[] hkl = lk.ToArray<string>();
foreach(string g3 in hkl)
{
if (g3.Contains(".txt"))
{
string fj = g3.Replace(".txt" + "", "");
us.Add(fj);
}
else
{
string fj = g3;
us.Add(fj);
}
}
string dir333 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1";
Grammar gr12 = new Grammar(new GrammarBuilder(us));
try
{
speechrecog1.RequestRecognizerUpdate();
speechrecog1.LoadGrammar(gr12);
speechrecog1.SpeechRecognized += speechrecog1_SpeechRecognized;
speechrecog1.SetInputToDefaultAudioDevice();
speechrecog1.RecognizeAsync(RecognizeMode.Single);
//speechrecog1.RecognizeAsyncStop();
//speechrecog.RecognizeAsync(RecognizeMode.Multiple);
//_completed.WaitOne(); // wait until speech recognition is completed
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
// timer2.Interval = 7000;
//timer2.Start();
// timer2.Interval = 5000;
//timer2.Start();
}
else
{
string speak = words[0] + words[1];
ss.SpeakAsync(speak);
}
}
}
else
{
ss.Speak(readText);
}
}
else
{
try
{
tabControl1.SelectedIndex = 1;
webBrowser1.Navigate("https://www.google.com/search?q=" + e.Result.Text.ToString());
}
catch (Exception ex)
{
string ggh = "Error"+ex;
}
}
}
/* SpeechRecognitionState = false;
timer1.Interval = 3000;
timer1.Start();
* */
textBox1.Text = "You: "+e.Result.Text.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
SpeechRecognitionState = true;
timer1.Stop();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void timer2_Tick(object sender, EventArgs e)
{
//loading the grammar again somehow make the recognition better
speechrecog.UnloadAllGrammars();
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
SpeechRecognitionState = true;
speechrecog1.RecognizeAsyncStop();
speechrecog1.UnloadAllGrammars();
timer2.Stop();
}
}
}
For example:
the text file how are you.txt contains:
i am fine. thank you.% how are you#good#bad
and the computer asks if im good and I reply with good. In the good.txt file:
Oh thats cool
the first time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(1 time)
the 2nd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 2 times)
the 3rd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 3 times)
How do i fix the repetition problem.

Thanks to #Nikolay Shmyrev I found the solution. As he said my event handler was firing twice. So inside it I put a:
try
{
//My code
}
finally
{
speechrecog1.SpeechRecognized -= speechrecog1_SpeechRecognized;
}

Related

Why when using filcesystemwatcher and dictionary with fileinfo it's throwing exceptions on wrong key and file not found?

Link for the repository on github :
https://github.com/chocolade1972/FileSystemWatcher
At the top i init with new instance both filelist and dic variables.
Then when starting watching i get all the files . and add them to the filelist and to the dic.
If for example the path is C:\ then filelist will contain 6 items :
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
Then in the event Watcher_Changes at this line :
var info = new FileInfo(e.FullPath);
There is exception the file not found and i see when using a breakpoint a long file temp type with tmp extension.
Then on other files it's throwing exceptions key was not present and then if i will start watching over again it will throw exceptions that the key is the same and already exist.
Other problem is now the button Button_doit in the event Button_doit_Click is not changing to stop and stay on start all the time.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace Watcher_WPF
{
/// <summary>
/// MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Watcher watcher;
private List<string> filelist = new List<string>();
private Dictionary<string, long> dic = new Dictionary<string, long>();
public MainWindow()
{
InitializeComponent();
CenterWindowOnScreen();
var nf = new NFilters()
{
Size = true,
FileName = true,
DirectoryName = true,
};
watcher = new Watcher(nf);
watcher.Created += Watcher_Changes;
watcher.Changed += Watcher_Changes;
watcher.Deleted += Watcher_Changes;
watcher.Renamed += Watcher_Renamed;
PrintMsg(Application.ResourceAssembly.ToString());
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (watcher.IsStarted)
{
e.Cancel = MessageBox.Show("Watcher is working, are you sure to close?", "Oh!",
MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No;
}
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
//Ctrl
if (e.KeyboardDevice.IsKeyDown(Key.LeftCtrl) || e.KeyboardDevice.IsKeyDown(Key.RightCtrl))
{
if (e.KeyboardDevice.IsKeyDown(Key.S))
{
//Ctrl+S
SaveLogs(null, null);
}
else if (e.KeyboardDevice.IsKeyDown(Key.D))
{
//Ctrl+D
ClearLogs(null, null);
}
}
}
private void Button_doit_Click(object sender, RoutedEventArgs e)
{
try
{
if (!watcher.IsStarted)
{
SetPath(textBox_path.Text.Trim());
}
watcher.IsStarted = !watcher.IsStarted;
if(button_doit.Content.ToString() == "Stop")
{
add_path.IsEnabled = true;
}
else
{
add_path.IsEnabled = false;
RandomFiles.GenerateFiles();
filelist = Directory.GetFiles(textBox_path.Text, "*.*").ToList();
foreach (var item in filelist)
{
FileInfo info = new FileInfo(item);
dic.Add(item, info.Length);
}
}
button_doit.Content = watcher.IsStarted ? "Stop" : "Start";
button_doit.Foreground = watcher.IsStarted ? Brushes.Red : Brushes.Black;
textBox_path.IsEnabled = !watcher.IsStarted;
PrintMsg(watcher.IsStarted ? "watcher started...At " + DateTime.Now.ToString() : "watcher stopped...At " + DateTime.Now.ToString());
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Button_options_Click(object sender, RoutedEventArgs e)
{
options.IsOpen = true;
}
private void OptionsMenu_Opened(object sender, RoutedEventArgs e)
{
allow_edit.IsChecked = !richTextBox_main.IsReadOnly;
topmost_switcher.IsChecked = Topmost;
filter_setter.IsEnabled = !watcher.IsStarted;
include_subdir.IsEnabled = !watcher.IsStarted;
include_subdir.IsChecked = watcher.IncludeSubdirectories;
}
private void AddPath(object sender, RoutedEventArgs e)
{
// Configure open file dialog box
var dialog = new Microsoft.Win32.OpenFileDialog();
dialog.FileName = "Document"; // Default file name
dialog.DefaultExt = ".*"; // Default file extension
dialog.Filter = "All files|*.*"; // Filter files by extension
// Show open file dialog box
bool? result = dialog.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
textBox_path.Text = dialog.FileName;
}
}
private void SaveLogs(object sender, RoutedEventArgs e)
{
try
{
SaveFileDialog sfd = new SaveFileDialog()
{
Filter = "TXT|*.txt",
FileName = $"watcher_{DateTime.Now:yyyyMMddHHmmss}"
};
if (sfd.ShowDialog() == true)
{
string path = sfd.FileName;
string content = new TextRange(
richTextBox_main.Document.ContentStart,
richTextBox_main.Document.ContentEnd).Text;
File.WriteAllText(path, content);
PrintMsg($"saved log to \"{path}\"");
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void ClearLogs(object sender, RoutedEventArgs e)
{
richTextBox_main.Document.Blocks.Clear();
}
private void Switch_Window_Topmost(object sender, RoutedEventArgs e)
{
Topmost = !Topmost;
}
private void Allow_edit_Click(object sender, RoutedEventArgs e)
{
richTextBox_main.IsReadOnly = !richTextBox_main.IsReadOnly;
}
private void Filter_setter_Click(object sender, RoutedEventArgs e)
{
var tmp = new FilterWindow(watcher.NFilters, watcher.Filter) { Owner = this }.ShowDialog();
if (tmp is Fdr fdr)
{
watcher.Filter = fdr.Filter;
watcher.NFilters = fdr.Nfilters;
PrintMsg($"set Filter: Size={watcher.NFilters.Size}, FileName={watcher.NFilters.FileName}, " +
$"DirectoryName={watcher.NFilters.DirectoryName}, Filter=\"{watcher.Filter}\"");
}
}
private void Include_subdir_Click(object sender, RoutedEventArgs e)
{
watcher.IncludeSubdirectories = !watcher.IncludeSubdirectories;
PrintMsg($"IncludeSubdirectories={watcher.IncludeSubdirectories}");
}
private void View_source_code_Click(object sender, RoutedEventArgs e)
{
Process.Start("https://github.com/Mzying2001/Watcher_WPF");
}
private void TextBox_path_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
Button_doit_Click(null, null);
}
private void RichTextBox_main_TextChanged(object sender, TextChangedEventArgs e)
{
if (richTextBox_main.IsReadOnly)
richTextBox_main.ScrollToEnd();
}
private void SetPath(string path)
{
watcher.Path = path;
PrintMsg($"set path: \"{watcher.Path}\"");
}
private void Watcher_Changes(object sender, FileSystemEventArgs e)
{
try
{
if (e.ChangeType == WatcherChangeTypes.Created || e.ChangeType == WatcherChangeTypes.Deleted)
{
}
else
{
var info = new FileInfo(e.FullPath);
var newSize = info.Length;
var oldsize = dic[e.FullPath];
string FileN1 = "File Name : ";
string FileN2 = info.Name;
string FileN3 = " Size Has Changed : From ";
string FileN4 = oldsize.ToString();
string FileN5 = " To ";
string FileN6 = newSize.ToString();
if (newSize != oldsize)
{
//string output = $"[*] {e.ChangeType}: \"{e.FullPath}\"";
Println(FileN1 + FileN2 + FileN3 + FileN4 + FileN5 + FileN6);
}
if (dic.ContainsKey(e.FullPath))
{
dic[e.FullPath] = info.Length;
}
else
{
dic.Add(e.FullPath, info.Length);
}
}
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Watcher_Renamed(object sender, RenamedEventArgs e)
{
try
{
Println($"[*] {e.ChangeType}: \"{e.OldFullPath}\" -> \"{e.FullPath}\"");
}
catch (Exception ex)
{
PrintErr(ex);
}
}
private void Println(string text, SolidColorBrush brush) => Dispatcher.Invoke(() =>
{
richTextBox_main.Document.Blocks.Add(new Paragraph(new Run(text) { Foreground = brush }));
});
private void Println(string text)
{
Println("[+] " + text + " At : " + DateTime.Now.ToString(), Brushes.LawnGreen);
}
private void PrintMsg(string message)
{
Println($"[+] {message}", Brushes.Yellow);
}
private void PrintErr(Exception e)
{
Println($"[-] {e}", Brushes.Red);
}
private void CenterWindowOnScreen()
{
double screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
double screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
double windowWidth = this.Width;
double windowHeight = this.Height;
this.Left = (screenWidth / 2) - (windowWidth / 2);
this.Top = (screenHeight / 2) - (windowHeight / 2);
}
private byte[] CheckSize(string filename)
{
using (MD5 md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
return md5.ComputeHash(stream);
}
}
}
private void textBox_path_TextChanged(object sender, TextChangedEventArgs e)
{
if (button_doit != null)
{
if (textBox_path.Text == "")
{
button_doit.IsEnabled = false;
}
else
{
button_doit.IsEnabled = true;
}
}
}
}
}

Multiple errors while trying to download with C#

Introduction:
Hello, I tried doing a program with a WinForms Application that downloads specific .zip files, but I get these errors:
UI look like
Errors what I get
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Net;
using System.Threading;
namespace Universal_Installer
{
public partial class Form1 : Form
{
WebClient wc;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog def = new FolderBrowserDialog();
def.RootFolder = Environment.SpecialFolder.Desktop;
def.Description = "Select installation location...";
def.ShowNewFolderButton = true;
if (def.ShowDialog() == DialogResult.OK)
{
textBox1.Text = def.SelectedPath;
}
}
private void Button2_Click(object sender, EventArgs e)
{
if (!Directory.Exists(textBox1.Text))
{
MessageBox.Show("The selected path does not exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (Directory.Exists(textBox1.Text))
{
string inst_size = "n/a";
string name = "n/a";
bool able = false;
string downloadlink = "n/a";
string PeoplePlaygroundSize = "0.161";
string PrisonArchitectSize = "0.586";
string AnotherBrickInTheMallSize = "0.164";
if (PP.Checked == true)
{
inst_size = PeoplePlaygroundSize;
downloadlink = "(A download link)";
name = "People Playground.zip";
able = true;
}
else if (PA.Checked == true)
{
inst_size = PrisonArchitectSize;
downloadlink = "(A download link)";
name = "Prison Architect.zip";
able = true;
}
else if (ABITM.Checked == true)
{
inst_size = AnotherBrickInTheMallSize;
downloadlink = "(A download link)";
name = "Another Brick In The Mall.zip";
able = true;
}
if (able == false)
{
MessageBox.Show("No checkboxes are checked!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (MessageBox.Show("Are you sure you want to install a " + inst_size + " GB game?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
status.Text = "Status: DOWNLOADING (" + inst_size + " GB)";
//////
ABITM.Enabled = false;
PP.Enabled = false;
PA.Enabled = false;
textBox1.Enabled = false;
button1.Enabled = false;
button2.Enabled = false;
//////
Thread thread = new Thread(() =>
{
Uri uri = new Uri(downloadlink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
wc.DownloadFileAsync(uri, textBox1.Text + "/" + filename);
});
thread.Start();
}
}
}
private void FileDownloadComplete(object sender,AsyncCompletedEventArgs e)
{
status.Text = "Status: IDLE";
PBAR.Value = 0;
MessageBox.Show("Download Completed (PATH: "+textBox1.Text+")", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);
ABITM.Enabled = true;
PP.Enabled = true;
PA.Enabled = true;
textBox1.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
wc = new WebClient();
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileCompleted += FileDownloadComplete;
}
private void wc_DownloadProgressChanged(object sender, AsyncCompletedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
PBAR.Minimum = 0;
double recive = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recive / total * 100;
PBAR.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}
}
}
Help:
Any help? By the way, if you see any text ending with .Text or .Value etc... these mean they are objects.
I really need your help by the way...
According the Official Documentation, the second argument for the DownloadProgressChanged must be DownloadProgressChangedEventArgs instead of AsyncCompletedEventArgs.
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
PBAR.Minimum = 0;
double recive = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recive / total * 100;
PBAR.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}

Why when trying to download the files again when clicking the start button I'm getting exception on the progressBar? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
namespace DownloadFiles
{
public partial class Form1 : Form
{
Stopwatch sw = new Stopwatch();
Stopwatch stopwatch = new Stopwatch();
string filesdirectory = "Downloaded_Files";
string mainurl = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/";
List<string> parsedlinks = new List<string>();
string path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
List<string> results = new List<string>();
List<string> urls = new List<string>();
string radarImageWebAddressP1;
string radarImageWebAddressP2;
public Form1()
{
InitializeComponent();
label3.Text = "";
label4.Text = "";
label5.Text = "";
label7.Text = "";
button2.Enabled = false;
button3.Enabled = false;
filesdirectory = Path.Combine(path_exe, filesdirectory);
if (!Directory.Exists(filesdirectory))
{
Directory.CreateDirectory(filesdirectory);
}
else
{
if (IsDirectoryEmpty(filesdirectory) == false)
{
button3.Enabled = true;
}
}
radarImageWebAddressP1 = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=";
radarImageWebAddressP2 = "&TotalImages=10&LangID=1&Location=";
for (int i = 0; i < 9; i++)
{
urls.Add(radarImageWebAddressP1 + i + radarImageWebAddressP2);
}
}
public bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private string downloadhtml(string url)
{
backgroundWorker1.ReportProgress(0, "Downloading Main Url");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string html = sr.ReadToEnd();
sr.Close();
response.Close();
StreamWriter w = new StreamWriter(path_exe + "\\page.html");
w.Write(html);
w.Close();
return html;
}
int Counter = 0;
int percentage = 0;
int total = 0;
int countfiletodownload = 0;
bool processStatus = false;
private void Parseanddownloadfiles()
{
//downloadhtml(mainurl);
if (bgw.CancellationPending == false)
{
/*backgroundWorker1.ReportProgress(0, "Parsing Links");
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/" + hrefValue;
parsedlinks.Add(url);
if (bgw.CancellationPending == true)
return;
}
}*/
parsedlinks = urls;
countfiletodownload = parsedlinks.Count;
total = parsedlinks.Count;
backgroundWorker1.ReportProgress(0, "Downloading Files");
processStatus = true;
for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
{
try
{
using (WebClient client = new WebClient())
{
sw.Start();
Uri uri = new Uri(parsedlinks[i]);
string filename = "RadarImage" + i.ToString() + ".gif";//parsedlinks[i].Substring(71);
client.DownloadFileAsync(uri, filesdirectory + "\\" + filename);
Counter += 1;
percentage = Counter * 100 / total;
string filenametoreport = filename.Substring(1);
countfiletodownload--;
backgroundWorker1.ReportProgress(percentage, filenametoreport);//countfiletodownload, filenametoreport);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
BackgroundWorker bgw;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bgw = (BackgroundWorker)sender;
if (bgw.CancellationPending == true)
{
return;
}
else
{
Parseanddownloadfiles();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState.ToString() == "Downloading Main Url")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Parsing Links")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Downloading Files")
{
label7.Text = countfiletodownload.ToString();//parsedlinks.Count.ToString();
label3.Text = e.UserState.ToString();
}
if (processStatus == true)
{
if (e.UserState.ToString() != "Downloading Files")
{
label4.Text = e.UserState.ToString();
label7.Text = countfiletodownload.ToString();
progressBar1.Value = e.ProgressPercentage;
/*using (var bitmap = new Bitmap(this.Width, this.Height))
{
this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"e:\screens\ss.gif" + countscreenshots, System.Drawing.Imaging.ImageFormat.Gif);
countscreenshots += 1;
}*/
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
}
else
{
label3.Text = "Download Completed";
stopwatch.Reset();
stopwatch.Stop();
timer1.Stop();
}
if(e.Cancelled)
label3.Text = "Operation Cancelled";
button1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "Cancelling Operation";
backgroundWorker1.CancelAsync();
button2.Enabled = false;
timer1.Stop();
stopwatch.Stop();
stopwatch.Reset();
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "";
label4.Text = "";
label7.Text = "";
backgroundWorker1.RunWorkerAsync();
timer1.Start();
stopwatch.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
Process.Start(filesdirectory);
}
private void timer1_Tick(object sender, EventArgs e)
{
label5.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed);
}
}
}
First time it's downloading fine but next time when clicking again the start button(button1) it's showing exception: System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
I tried to reset the progressBar value to 0 in the start button(button1) click event but it didn't solve the problem.
ArgumentOutOfRangeException: Value of '111' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'.
Parameter name: Value
The ArgumentOutOfRange exception is because you never reset Counter:
You define Counter as class level variable and initialize to 0:
int Counter = 0;
Then in your loop you call:
Counter += 1;
percentage = Counter * 100 / total;
When you click the button to restart the download, Counter still holds the final value of the previous run.
In button1_Click, prior to calling RunWorkerAsync
You need to reset it:
Counter = 0;

Regarding strongly typed dataset in windows form application

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace GST.Masters
{
public partial class Customers : Heptanesia.Winforms.Ui.Forms.MainUC
{
public static string recCode
{ get; set; }
public string RC;
public bool insertFlag;
public Data.GSTDb.CustomersRow r;
public Data.GSTDb.CustomersGSTNosRow gr;
public Data.GSTDb.CustomersDataTable dt = new Data.GSTDb.CustomersDataTable();
public Customers()
{
InitializeComponent();
recCode = Guid.NewGuid().ToString();
this.Load += new EventHandler(this.Customers_Load);
this.Ts.SaveClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SaveClickedEventHandler(this.Ts_SaveClicked);
this.Ts.AddNewClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.AddNewClickedEventHandler(this.Ts_AddNewClicked);
this.Ts.SearchClicked += new Heptanesia.Winforms.Ui.Menu.ToolStrip.SearchClickedEventHandler(this.Ts_SearchClicked);
this.DgGST.CellValidated += (sender, e) =>
{
string name = this.DgGST.Columns[e.ColumnIndex].Name;
if (name == "DGCCountryCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.statesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCStateCode"].Value = null;
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
else if (name == "DGCStateCode")
{
name = this.DgGST.Rows[e.RowIndex].Cells[name].Value.ToString();
this.citiesBindingSource.Filter = "ParentCode = '" + name + "'";
if (!this.FormIsLoading)
{
this.DgGST.Rows[e.RowIndex].Cells["DGCCityCode"].Value = null;
}
}
};
}
private void Ts_AddNewClicked(object sender, EventArgs e)
{
this.gSTDb.Customers.Rows.Clear();
r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter CGT = new Data.GSTDbTableAdapters.CustomersGSTNosTableAdapter();
CGT.FillByParentCode(gSTDb.CustomersGSTNos, r.RecCode);
}
private void Ts_SearchClicked(object sender, EventArgs e)
{
Heptanesia.Winforms.Ui.Forms.SearchForm sf = new Heptanesia.Winforms.Ui.Forms.SearchForm();
sf.DataSource = new Data.GSTDbTableAdapters.CustomersTableAdapter().GetData();
sf.DisplayColumns = new string[] { "Name" };
sf.DisplayHeaders = new string[] { "Customers Name" };
sf.DisplayWidths = new int[] { 200 };
if (sf.ShowDialog(this) == DialogResult.OK)
{
this.RC = sf.ReturnRow["RecCode"].ToString();
this.customersTableAdapter.FillByRecCode(this.gSTDb.Customers, RC);
}
}
private void Ts_SaveClicked(object sender, EventArgs e)
{
string message = "Error: ";
try
{
this.customersBindingSource.EndEdit();
//if (this.DgGST.CurrentRow.DataBoundItem != null)
this.fkCustomerGSTNosCustomersBindingSource.EndEdit();
if (this.gSTDb.Customers.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.customersBindingSource, this.gSTDb.Customers.GetErrors()[0]);
else if (this.gSTDb.CustomersGSTNos.HasErrors)
message += Classes.Global.SetBindingSourcePositionAndGetError(this.fkCustomerGSTNosCustomersBindingSource, this.gSTDb.CustomersGSTNos.GetErrors()[0]);
else
{
this.gSTDb.Customers.BeforeSave();
this.gSTDb.CustomersGSTNos.BeforeSave();
Data.GSTDbTableAdapters.TableAdapterManager tm = new Data.GSTDbTableAdapters.TableAdapterManager();
tm.CustomersTableAdapter = this.customersTableAdapter;
tm.CustomersGSTNosTableAdapter = this.customersGSTNosTableAdapter;
tm.UpdateAll(this.gSTDb);
message = "Record(s) Saved Successfully";
}
}
catch (Exception ex)
{
message += ex.Message;
}
MessageBox.Show(message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void Customers_Load(object sender, EventArgs e)
{
this.FormIsLoading = true;
this.customersTableAdapter.Fill(this.gSTDb.Customers);
this.customersGSTNosTableAdapter.Fill(this.gSTDb.CustomersGSTNos);
this.countriesTableAdapter.Fill(this.gSTDb.Countries);
this.statesTableAdapter.Fill(this.gSTDb.States);
this.citiesTableAdapter.Fill(this.gSTDb.Cities);
this.gSTDb.Customers.Rows.Clear();
if (this.gSTDb.Customers.Rows.Count == 0)
{
Data.GSTDb.CustomersRow r = this.gSTDb.Customers.NewCustomersRow();
this.gSTDb.Customers.AddCustomersRow(r);
}
this.FormIsLoading = false;
}
private void DgGST_DataError(object sender, DataGridViewDataErrorEventArgs e)
{
if (e.Exception is ArgumentException)
{
object value = DgGST.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (!((DataGridViewComboBoxColumn)DgGST.Columns[e.ColumnIndex]).Items.Contains(value))
{
((DataGridViewComboBoxCell)DgGST[e.ColumnIndex, e.RowIndex]).Value = DBNull.Value;
//((DataGridViewComboBoxColumn)dgv.Columns[e.ColumnIndex]).Items.Add(value);
e.ThrowException = false;
}
}
else
{
MessageBox.Show(e.Exception.Message);
e.Cancel = true;
}
}
}
}
I am developing one simple invoice application in which I am having a simple Customer screen module.A Customer can have any number of GST records in the Datagridview.The Screen is based on Customer Masters(Textboxes) and Customers Master Details(Datagridview) relationship through foreign keys. And I am Using Strongly Typed Dataset in this project as a xsd file.This Screen has 3 buttons i.e.New,Save and Find toolstrip menu.
When I start adding records after clicking on New Buttonstrip and and save ,it saves it successfully and when I press New Ideally it should clear the rows.The main issue here is that it is not clearing the rows??
I am enclosing the cs file here.
What I have tried:
Everything as I can Do.
Clearing the Rows through Rows.Clear(); 2) I tried clearing
Binding Source and DataGridview after setting it null.
Nothing Worked.

How can I save the path of an image in OpenFileDialog to a string?

I am currently working on a small DB project in which I have tried implementing a browser for image so that they can be saved for each player accordingly.
I am particularly struggling with wring the path of the image to a string, and the storing that string into the arraylist which will then be used to load the file by using the path stored in that arraylist. As you see in the code I have tried to assign the OpenFd.FileName to a string called pathToImage but it doesn't work, the string remains empty after a quick debug check using MessageBox.Show(pathToImage)
Can anyone help me?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Collections;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Formatters.Binary;
namespace Assignment1_Template2
{
public partial class Form1 : Form
{
// =======================The data Structure ===========================
// ========Uses [SERIALIZABLE] to allow simple loading/saving ==========
[Serializable]
private struct myStruct
{ // The "constructor". Fills data structure with default values
public myStruct(int playerId)
{
uniquePlayerId = new int[playerId];
playerIgName = "";
contactStreet = "";
contactTown = "";
contactPostcode = "";
contactEmail = "";
contactTelephone = "";
imagePath = "";
for (int i = 0; i < playerId; ++i) uniquePlayerId[i] = 0;
}
// The data types of the struct
public int[] uniquePlayerId;
public string playerIgName;
public string contactStreet;
public string contactTown;
public string contactPostcode;
public string contactEmail;
public string contactTelephone;
public string imagePath;
}
// ================== End of data Structure definition ===================
// =======================================================================
// ================ Global Variables used in the Program =================
private ArrayList dataList; // This is the main data collection
private int currentEntryShown = 0; // current myStruct on display
private int numberOfEntries = 0; // total number of myStructs
private string filename = "C:\\test.dat"; // path of the file being read in
public string pathToImage = "";
public string pathToImagePlaceholder = "";
// =======================================================================
// ================== STARTING POINT FOR THE PROGRAM =====================
public Form1()
{
// Brings up the window.
InitializeComponent();
// Create the ArrayList
dataList = new ArrayList();
// Call methods implemented below
LoadData();
ShowData();
UpdatePrevNextBtnStatus();
}
// =========================================================================
// =================== END OF STARTING POINT FOR PROGRAM ===================
// ========= All further events are now triggered by user actions ==========
// =========================================================================
// =========================================================================
// ========================= BUTTON ACTION HANDLERS ========================
// =========================================================================
private void showPreviousBtn_Click(object sender, EventArgs e)
{
--currentEntryShown;
ShowData();
UpdatePrevNextBtnStatus();
}
private void showNextBtn_Click(object sender, EventArgs e)
{
++currentEntryShown;
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void addNewPlayerBtn_Click(object sender, EventArgs e)
{
++numberOfEntries; // "Add" clicked: we need to create one more entry
currentEntryShown = numberOfEntries - 1; // scroll to an empty record at the end
// Create a new data structure, its constructor will fill it with default values
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct); // add the frshly created struct to the ArrayList
ShowData(); // display
addNewPlayerBtn.Enabled = true; // can't do this again before saving
UpdatePrevNextBtnStatus();
}
private void SaveBtn_Click(object sender, EventArgs e)
{
SaveData(); // Call the Save() method implemented below
addNewPlayerBtn.Enabled = true; // After saving we can add another new record
UpdatePrevNextBtnStatus(); // Set 'Next' and 'Previous' button appearance
}
// =========================================================================
// =========================================================================
// ================ HANDLE DATA CHANGES BY USER ============================
// =========================================================================
// If the text box string is changed by the user, update
private void playerIdBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.uniquePlayerId[0] = Convert.ToInt32(playerIdBox.Text);
dataList[currentEntryShown] = aNewStruct;
}
private void playerIgNameBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.playerIgName = playerIgNameBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactStreetBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactStreet = contactStreetBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTownBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTown = contactTownBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactPostcodeBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactPostcode = contactPostcodeBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactEmailBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactEmail = contactEmailBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
private void contactTelephoneBox_TextChanged(object sender, EventArgs e)
{
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.contactTelephone = contactTelephoneBox.Text;
dataList[currentEntryShown] = aNewStruct;
}
// =========================================================================
// ================= HELPER METHODS FOR DISPLAYING DATA ====================
// =========================================================================
private void ShowData()
{
playerIdBox.Text = ((myStruct)dataList[currentEntryShown]).uniquePlayerId[0].ToString();
playerIgNameBox.Text = ((myStruct)dataList[currentEntryShown]).playerIgName;
contactStreetBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactStreet;
contactTownBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTown;
contactPostcodeBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactPostcode;
contactEmailBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactEmail;
contactTelephoneBox.Text = "" + ((myStruct)dataList[currentEntryShown]).contactTelephone;
pathToImagePlaceholder = "" + ((myStruct)dataList[currentEntryShown]).imagePath;
MessageBox.Show(pathToImagePlaceholder);
try
{
playerPictureBox.Image = Image.FromFile(pathToImagePlaceholder);
}
catch
{
return;
}
}
private void UpdatePrevNextBtnStatus()
{
if (currentEntryShown > 0) showPreviousBtn.Enabled = true;
else showPreviousBtn.Enabled = false;
if (currentEntryShown < (numberOfEntries - 1)) showNextBtn.Enabled = true;
else showNextBtn.Enabled = false;
label1.Text = "Player ID";
label3.Text = (currentEntryShown + 1) + " / " + numberOfEntries;
}
// =========================================================================
// =========================================================================
// =============== HELPER METHODS FOR LOADING AND SAVING ===================
// =========================================================================
private void SaveData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
try
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, dataList);
MessageBox.Show("Data saved to " + filename, "FILE SAVE OK", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Could not serialise to " + filename,
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
fs.Close();
}
catch
{
MessageBox.Show("Could not open " + filename +
" for saving.\nNo access rights to the folder, perhaps?",
"FILE SAVING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void LoadData()
{
try
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
try
{
BinaryFormatter bf = new BinaryFormatter();
dataList = (ArrayList)bf.Deserialize(fs);
currentEntryShown = 0;
numberOfEntries = dataList.Count;
}
catch
{
MessageBox.Show("Could not de-serialise from " + filename +
"\nThis usually happens after you changed the data structure.\nDelete the data file and re-start program\n\nClick 'OK' to close the program",
"FILE LOADING PROBLEM", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
fs.Close(); // close file
Environment.Exit(1); // crash out
}
fs.Close();
}
catch
{
if (MessageBox.Show("Could not open " + filename + " for loading.\nFile might not exist yet.\n(This would be normal at first start)\n\nCreate a default data file?",
"FILE LOADING PROBLEM", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
// No data exist yet. Create a first entry
myStruct aNewStruct = new myStruct(5);
dataList.Add(aNewStruct);
numberOfEntries = 1;
currentEntryShown = 0;
}
}
}
// =========================================================================
// =========================================================================
// ====================== HELPER METHODS FOR SORTING =======================
// =========================================================================
// This function will sort by player name by using the PlayerNameComparer below
private void sortToolStripMenuItem_Click(object sender, EventArgs e)
{
dataList.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
// Overriding (= overwriting) the default IComparer
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((myStruct)x).playerIgName.CompareTo(((myStruct)y).playerIgName);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
SaveData();
UpdatePrevNextBtnStatus();
}
private void deletePlayerBtn_Click(object sender, EventArgs e)
{
dataList.RemoveAt(currentEntryShown);
SaveData();
if (currentEntryShown != dataList.Count)
{
ShowData();
}
UpdatePrevNextBtnStatus();
}
private void searchToolStripMenuItem_Click(object sender, EventArgs e)
{
Form searchForm = new Form1();
searchForm.Show();
}
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
pathToImage = OpenFd.FileName;
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = pathToImage;
dataList[currentEntryShown] = aNewStruct;
// save the FileName to a string.
}
MessageBox.Show(pathToImage);
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
}
}
Set pathToImage after the ShowDIalog has completed, not before:
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
pathToImage = OpenFd.FileName; ...
I could be wrong because reading all that wall of code requires too much time, but your last method should be
private void uploadButton_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog OpenFd = new OpenFileDialog();
// REMOVED HERE .... pathToImage = OpenFd.FileName
OpenFd.Filter = "Images only. |*.jpeg; *.jpg; *.png; *.gif;";
DialogResult rd = OpenFd.ShowDialog();
if (rd == System.Windows.Forms.DialogResult.OK)
{
playerPictureBox.Image = Image.FromFile(OpenFd.FileName);
myStruct aNewStruct = new myStruct(5);
aNewStruct = (myStruct)dataList[currentEntryShown];
aNewStruct.imagePath = OpenFd.FileName; // Changed this line...
dataList[currentEntryShown] = aNewStruct;
}
// no much sense this here if the user cancel the dialogbox
// MessageBox.Show(pathToImage);
}

Categories