How can I change Form Elements in C# within a method - c#

I have a Windows Forms Application which has some Buttons and Labels.
Inside the public partial class Form1 I created some methods.
Inside those methods I want to set the text for Label1 for example.
I tried creating a new form inside the method by doing
Form1 frm = new Form1();
and then tried setting it with
frm.label1.text = "something";
but this didn't change the label text. I also set the modifier of the label to "Public", this didn't help either.
When I showed the form with
frm.Show();
the same form opened a second time, with the changed text of the label. But I'd like to change the label text in the existing form. How would I approach this or what would be best practice in this case?
Here is a my button click event:
private void updatebutton_Click(object sender, EventArgs e)
{
DoUpdate();
}
and this is the method I am calling with the button click:
static void DoUpdate()
{
string addon_path = #"\Interface\AddOns\";
string fullpath = gamefolder.Text + addon_path;
string filePath = #"C:\temp\redact.zip";
if (currentversion.Text == "n/a")
{
GetCurrentVersion(currentversion);
}
string downloadUrl = "https://SOMEURL" + frm.currentversion.Text + ".zip";
WebClient client = new WebClient();
client.DownloadProgressChanged += (s, e) =>
{
progressBar1.Value = e.ProgressPercentage;
};
client.DownloadFileCompleted += (s, e) =>
{
string filePath = #"C:\temp\redact.zip";
if (File.Exists(filePath))
{
File.Delete(filePath);
}
string ExtractPath = #"C:\temp\redact-" + currentversion.Text;
System.IO.Compression.ZipFile.ExtractToDirectory(filePath, ExtractPath);
if (Directory.Exists(fullpath + "redact"))
{
Directory.Delete(fullpath + "redact", true);
Directory.Delete(fullpath + "redact_Options", true);
Directory.Delete(fullpath + "redact_Libraries", true);
}
Directory.Move(ExtractPath + #"\redact", fullpath + "redact");
Directory.Move(ExtractPath + #"\redact_Libraries", fullpath + "redact_Libraries");
Directory.Move(ExtractPath + #"\redact_Options", fullpath + "redact_Options");
Directory.Delete(ExtractPath);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
};
client.DownloadFileAsync(new Uri(downloadUrl), filePath);
}

Related

C# help couldn't find the path (LOG IN SYSTEM)

So my program is working well but whenever i sign up on Form 2 it says that it couldn't find the path i don't know what's wrong please help i need to pass it later , i don't know if i need to make a new folder on the C: just to get the LOGIN.ID
{
public partial class Form1 : Form
{
public string username, password;
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Show();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
var sr = new System.IO.StreamReader("C\\" + textBox1.Text + "\\login.ID");
username = sr.ReadLine();
password = sr.ReadLine();
sr.Close();
if (username == textBox1.Text && password == textBox2.Text)
MessageBox.Show("Log-in Successfull", "Success!");
else
MessageBox.Show("Username or password is wrong! ","Error!");
}
catch (System.IO.DirectoryNotFoundException )
{
MessageBox.Show("The user doesn't exist!", "Error!");
}
}
}
}
//form 2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
var sw = new System.IO.StreamWriter ("C\\" + textBox1.Text + "\\login.ID");
sw.Write(textBox1.Text + "\n" + textBox2.Text);
sw.Close();
}
catch(System.IO.DriveNotFoundException )
{
System.IO.Directory.CreateDirectory("C:\\" + textBox1.Text);
var sw = new System.IO.StreamWriter("C\\" + textBox1.Text + "\\login.ID");
sw.Write(textBox1.Text + "\n" + textBox2.Text);
sw.Close();
}
}
}
}
You're missing the : after the C drive in many places in your code
var sw = new System.IO.StreamWriter("C\\" + textBox1.Text + "\\login.ID");
change to
var sw = new System.IO.StreamWriter("C:\\" + textBox1.Text + "\\login.ID");
You should take a close look at your paths. i don't think c\ exists.
Probably you are using C:\
If you still have problems maybe your TextBox1.Text returns a wrong path.

How do I make the streamWriter write a new file in the same folder C# .NET

I have 3 forms.. Only 2 which I am using.
The registerForm, loginForm and mainForm.
This is how everything is set up.
Application opens and prompts the user with the login form > User can either log in to a existing account or press register > user logs in > streamWriter creates a text file with the users username and password > textfile stores at
("C:\" + regUsernametextBox.Text + "\infoBox.creds"). Keep in mind that the ("infoBox.creds") is just an extension that I made.
User can type stuff into the mainForm's textbox which is called textBox1
I want the streamWriter to write a textfile of the content that is inside of the textBox1 into the same folder as the user credentials are.
Example
I create a user named Tom > The application creates a folder names Tom with a textfile in it, and that textfile contains the username and password of the user.
When the user that is logged in writes something in the textBox1 I want it to save that text to another textfile but in the same folder which would be the "Tom" folder.
What I have tried
What I have done (as you can see below) is that i've tried storing the value of the username from the loginForm and tried using that value in my mainForm
Giving the file a name
var streamWrite = new System.IO.StreamWriter("C:\\" + loginFrm.folderName + "\\Conent.info");
And then storing the value in it
System.IO.Directory.CreateDirectory("C:\\" + loginFrm.folderName);
var streamWrite = new System.IO.StreamWriter("C:\\" + loginFrm.folderName + "\\Conent.info");
streamWrite.Write(textboxContent);
But it doesnt write a textfile with the information that has been given to the textBox1 in the mainForm.
I hope I described my issue well and I appriciate any help possible!
mainForm Code
public partial class mainForm : MetroForm
{
public mainForm()
{
InitializeComponent();
}
public string textboxContent;
private void Form1_Load(object sender, EventArgs e)
{
textbox1.Text = Properties.Settings.Default.SavedText;
loginForm loginFrm = new loginForm();
loginFrm.Hide();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
loginForm loginFrm = new loginForm();
textboxContent = textbox1.Text;
try
{
var streamWrite = new System.IO.StreamWriter("C:\\" + loginFrm.folderName + "\\Conent.info");
streamWrite.Write(textboxContent);
streamWrite.Close();
}
catch(System.IO.DirectoryNotFoundException ex)
{
System.IO.Directory.CreateDirectory("C:\\" + loginFrm.folderName);
var streamWrite = new System.IO.StreamWriter("C:\\" + loginFrm.folderName + "\\Conent.info");
streamWrite.Write(textboxContent);
streamWrite.Close();
MessageBox.Show("Nope");
}
loginForm Code
public loginForm()
{
InitializeComponent();
}
public string username, password;
public string folderName;
private void button1_Click(object sender, EventArgs e)
{
try
{
folderName = username;
var sr = new System.IO.StreamReader("C:\\" + regUsernametextBox.Text + "\\infoBox.creds");
username = sr.ReadLine();
password = sr.ReadLine();
sr.Close();
if(username == regUsernametextBox.Text && password == regPasswordTextBox.Text)
{
MessageBox.Show("You have successfully logged in", "Authorize");
loginForm regFrm = new loginForm();
this.Hide();
mainForm mainFrm = new mainForm();
mainFrm.ShowDialog();
this.Show();
}
else
{
MessageBox.Show("Please make sure you typed int he correct name and password", "Authorize Error!");
}
}
catch(System.IO.DirectoryNotFoundException ex)
{
MessageBox.Show("The user does not exist","Error");
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void registerLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
registerForm regFrm = new registerForm();
regFrm.Visible = true;
}
}
}
registerForm Code
public registerForm()
{
InitializeComponent();
}
private void registerForm_Load(object sender, EventArgs e)
{
}
private void registerButton_Click(object sender, EventArgs e)
{
try
{
var sw = new System.IO.StreamWriter("C:\\" + regUsernametextBox.Text + "\\infoBox.creds");
sw.Write(regUsernametextBox.Text + "\n" + regPasswordTextBox.Text);
sw.Close();
}
catch(System.IO.DirectoryNotFoundException ex)
{
System.IO.Directory.CreateDirectory("C:\\" + regUsernametextBox.Text);
var sw = new System.IO.StreamWriter("C:\\" + regUsernametextBox.Text + "\\infoBox.creds");
sw.Write(regUsernametextBox.Text + "\n" + regPasswordTextBox.Text);
MessageBox.Show("Account successfully created!","Account");
sw.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
When your mainForm is closing
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
loginForm loginFrm = new loginForm();
Your create a new loginForm, Which is blank and the value loginFrm.folderName should be null or an empty string (I don't see the constructor of loginForm).
You need the original reference of the loginForm with the entered data, or at least the folderName.
So in your mainForm create a variable that can catch the folder name
public partial class mainForm : MetroForm
{
public string User_folder_Name;
When you call the mainForm in the loginForm pass first the value:
mainForm mainFrm = new mainForm();
mainFrm.User_folder_Name = folderName;
mainFrm.ShowDialog();
And now you can use it in the closing event of your mainForm.
I would also suggest using a "using" block.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
loginForm loginFrm = new loginForm();
textboxContent = textbox1.Text;
// Path.Combine is a conmfortable tool to create paths
string completeFolderPath = Path.Combine(#"C:\", User_folder_Name);
string completeFIlePath = Path.Combine(completeFolderPath, "Conent.info");
using (StreamWriter writer = new StreamWriter(completeFIlePath))
{ // check whether the directory exists and create on if NOT
if (!Directory.Exists(completeFolderPath))
{
Directory.CreateDirectory(completeFolderPath);
MessageBox.Show("Directory created");
}
// write the content
streamWrite.Write(textboxContent);
}
}
EDIT:
in your loginForm you have the three variables
public string username, password;
public string folderName;
when the form is created with the new keyword. All those values are null in the beginning, because you don't assign explicitly values to them.
In the button click event you do this:
folderName = username;
which is basically assigning a variable which is null to another variable which is also null. So the result is null
when you then read the file you fill only username but the value is never passed to foldername, which is still null.
Please exchange the order of the two lines. like this:
var sr = new System.IO.StreamReader("C:\\" + regUsernametextBox.Text + "\\infoBox.creds");
username = sr.ReadLine();
password = sr.ReadLine();
folderName = username;
sr.Close();

Refresh ComboBox directory listing in WinForm, onClick for C#

I have a set-up a Windows form that on completion creates a .txt document containing imputed data for the user on one form and then that form can then be opened into a richTextBox on another form using a ComboBox as a selection tool.
The problem I am having is that the ComboBox does not refresh the directory listings where the .txt documents are saved after a new .txt has been created and so the user has to restart the program before it shows up in the ComboBox listing, wondering how to solve this. Possibly force the ComboBox to refresh the listings onClick of a button?
Form with ComboBox selection method on:
public Default()
{
InitializeComponent();
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.Show();
}
private void ModuleSelectorComboBox_SelectedValueChanged(object sender, EventArgs e)
{
richTextBox1.Clear(); //Clears previous Modules Text
string fileName = (string)ModuleSelectorComboBox.SelectedItem;
string filePath = Path.Combine(#"C:\Modules\", fileName + ".txt");
if (File.Exists(filePath))
richTextBox1.AppendText(File.ReadAllText(filePath));
else
MessageBox.Show("There's been a problem. Please restart the program. \nError 1", "Error 1", //error 1 is file deleted while the program is running
MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
}
To add I want to avoid the using of the Dialog save/open file method and is why I am using the ComboBox to do this.
Thanks in advance.
The form to create new .txt document (I don't see this as essentially needed I have just added it for reference):
private void button5_Click(object sender, EventArgs e)
{
RichTextBox newbox = new RichTextBox();
{
String Saved_Module = Path.Combine("C:\\Modules", txtModuleName.Text + ".txt");
newbox.AppendText(txtModuleName.Text + "\n" + ModuleDueDate.Text + "\n" + txtModuleInfo.Text + "\n" + txtModuleLO.Text);
newbox.SaveFile(Saved_Module, RichTextBoxStreamType.PlainText);
Directory.CreateDirectory(Path.Combine(#"C:\Modules", txtModuleName.Text));
this.Close();
}
}
First of all, encapsulate the logic of the combobox population in a method.
public Default()
{
InitializeComponent();
LoadComboBox();
}
void LoadComboBox()
{
ModuleSelectorComboBox.Items.Clear();
string[] files = Directory.GetFiles(#"C:\Modules");
foreach (string file in files)
ModuleSelectorComboBox.Items.Add(Path.GetFileNameWithoutExtension(file));
}
I suggest to open the form as a dialog form using ShowDialog method
and set the DialogResult to DialogResult.OK in the button5_Click method.
private void button5_Click(object sender, EventArgs e)
{
RichTextBox newbox = new RichTextBox();
String Saved_Module = Path.Combine("C:\\Modules", txtModuleName.Text + ".txt");
newbox.AppendText(txtModuleName.Text + "\n" + ModuleDueDate.Text + "\n" + txtModuleInfo.Text + "\n" + txtModuleLO.Text);
newbox.SaveFile(Saved_Module, RichTextBoxStreamType.PlainText);
Directory.CreateDirectory(Path.Combine(#"C:\Modules", txtModuleName.Text));
this.DialogResult = DialogResult.OK;
this.Close();
}
And then, based on the DialogResult load or do not load the combobox's items in the moduleToolStripMenuItem_Click method.
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.ShowDialog();
if (result == DialogResult.OK)
{
LoadComboBox();
}
}
Update:
If you don't want to use a Dialog, you can subscribe to an FormClosing event and update the combobox in a handler to the event.
private void moduleToolStripMenuItem_Click(object sender, EventArgs e)
{
NewModule newmodule = new NewModule();
newmodule.FormClosing += F_FormClosing
newmodule.Show();
}
private void F_FormClosing(object sender, FormClosingEventArgs e)
{
LoadComboBox();
}
I suggest breaking out LoadComboBox as Valentin suggests, but using a FileSystemWatcher instantiated and disposed with the form to monitor the Modules directory and call LoadComboBox on any create/delete.

How to pass a value from one function to another in event handler methods in c#

I have list box populated using web-client and I used , for-loop to separate object from json response for my use ,I need to use those objects throughout the class ,i.e I need to use those values in all the methods,It will be even feasible if can Pass from one method to another
Code:
void Downloadpage()
{
WebClient webclient = new WebClient();
webclient.Headers["ContentType"] = "application/json";
webclient.DownloadStringCompleted += wc_downloadStringCompleted;
webclient.DownloadStringAsync(new Uri("http://client.web.net/pages_wp.php"), UriKind.RelativeOrAbsolute);
}
public void wc_downloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string lreport = e.Result.ToString();
string lnoHTMLs = Regex.Replace(lreport, #"<[^>]+>| |‌|»|«|“|\\n|\\t|", "", RegexOptions.Multiline).Trim();
string lnoHTMLNormaliseds = Regex.Replace(lnoHTMLs, #"\s{2,}", " ");
JArray res = JArray.Parse(lnoHTMLNormaliseds);
news = new List<jsons>();
string rId = res[0]["raportId"].ToString(); ---->a
string rTitle = res[0]["raportTitle"].ToString(); --->b
news.Add(new jsons() { raportId = rId, raportTitle = rTitle});
Presslist.ItemsSource = news;
}
I need to access values in 'a'and 'b' in another button click event as below
private void Add_to_cart(object sender, EventArgs e)
{
//values need to come here
}
Note: Add_to_cart is triggered on button click
Make the variables class level
String _rId ="";
String _rTitle ="";
void Downloadpage()
{
WebClient webclient = new WebClient();
webclient.Headers["ContentType"] = "application/json";
webclient.DownloadStringCompleted += wc_downloadStringCompleted;
webclient.DownloadStringAsync(new Uri("http://client.web.net/pages_wp.php"),
UriKind.RelativeOrAbsolute);
}
public void wc_downloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string lreport = e.Result.ToString();
string lnoHTMLs = Regex.Replace(lreport, #"<[^>]+>| |‌|»|«|“|\\n|\\t|", "", RegexOptions.Multiline).Trim();
string lnoHTMLNormaliseds = Regex.Replace(lnoHTMLs, #"\s{2,}", " ");
JArray res = JArray.Parse(lnoHTMLNormaliseds);
news = new List<jsons>();
string rId = res[0]["raportId"].ToString(); // ---->a
string rTitle = res[0]["raportTitle"].ToString(); // --->b
news.Add(new jsons() { raportId = rId, raportTitle = rTitle});
_rId = rId;
_rTitle = rTitle;
Presslist.ItemsSource = news;
}
private void Add_to_cart(object sender, EventArgs e)
{
//values need to come here
//_rId
//_rTitle
}
I think the place where you are calling your Downloadpage() method can save these values in a common place. May be Session Level or Application level space.
I think that Add_to_cart() method is a button click event so the DownloadPage should be called in page load event or any event prior to display the UI.
And when the Add_to_cart() is called than you can retrieve the values and use them.

BackgroundWorker & Progressbar Issues c# Visual Studio 2010

Im trying to get my head around backgroundworker and the progressbar, so far i have got it to work but not exactly how i want it to work. Basically i am sorting/renaming folders and copying them to a different location, this works and the code is self explanatory, the output folders generated are as expected. However for each folder i intend to search through i have to right click it to get the number of files and then in the code i have to set the progressBar1.Maximum to that value in order for it to show the coreect progression of the progress bar. How is it possible to get this to set the number of files automatically since it goes through each folder anyway? Some folders have thousands of files and others have millions. beyond this i want to add a label so that it displays the name of the file it is processing along with the progressbar updates.
namespace Data_Sorter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tbFilePath.Text = folderBrowserDialog1.SelectedPath.ToString();
}
private void btnSort_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int totalFiles = 0;
foreach (var file in Directory.GetFiles(tbFilePath.Text, "*.txt", SearchOption.AllDirectories))
{
backgroundWorker1.ReportProgress(totalFiles);
string fullFilename = file.ToString();
string[] pathParts = fullFilename.Split('\\');
string date = pathParts[6];
string fileName = pathParts[7];
string[] partName = fileName.Split('_');
string point = partName[3];
Directory.CreateDirectory("Data Sorted Logs\\" + point + "\\" + date + "\\");
if (Directory.Exists(("Data Sorted Logs\\" + point + "\\" + date + "\\")))
{
string destPath = (point + "\\" + date + "\\");
File.Copy(fullFilename, "C:\\Documents and Settings\\PC\\Desktop\\Sorter\\Data Sorter\\bin\\Debug\\Data Sorted Logs\\" + destPath + fileName); }
else
{
MessageBox.Show("destination folder not found " + date + point);
}
totalFiles++;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Maximum = 6777; // set this value at the maximum number of files you want to sort //
progressBar1.Value = e.ProgressPercentage;
}
}
You can find out the file number simply reading the GetFiles length.
You can pass the relative percentage using the expression: (i * 100) / totalFiles, in this way it's not necessary to set the Maximum value for the progress.
You can also report the filename to the progressbar passing it as the UserState in the progressChanged event.
Try the code below:
namespace Data_Sorter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnSelect_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tbFilePath.Text = folderBrowserDialog1.SelectedPath.ToString();
}
private void btnSort_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int totalFiles = 0;
string[] files = Directory.GetFiles(tbFilePath.Text, "*.txt", SearchOption.AllDirectories);
totalFiles = files.Length;
int i = 0;
foreach (var file in files)
{
backgroundWorker1.ReportProgress((i * 100) / totalFiles, file);
i++
string fullFilename = file.ToString();
string[] pathParts = fullFilename.Split('\\');
string date = pathParts[6];
string fileName = pathParts[7];
string[] partName = fileName.Split('_');
string point = partName[3];
Directory.CreateDirectory("Data Sorted Logs\\" + point + "\\" + date + "\\");
if (Directory.Exists(("Data Sorted Logs\\" + point + "\\" + date + "\\")))
{
string destPath = (point + "\\" + date + "\\");
File.Copy(fullFilename, "C:\\Documents and Settings\\PC\\Desktop\\Sorter\\Data Sorter\\bin\\Debug\\Data Sorted Logs\\" + destPath + fileName); }
else
{
MessageBox.Show("destination folder not found " + date + point);
}
totalFiles++;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Done");
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
progressBar1.Text = e.UserState.ToString();//or yourNewLabel.Text = e.UserState.ToString();
}
}
Move the call to GetFiles up so you can get the length of the array it returns:
string[] files = Directory.GetFiles(tbFilePath.Text, "*.txt",
SearchOption.AllDirectories));
// Note - you won't be able to set this UI property from DoWork
// because of cross-thread issues:
// progressbar1.Maximum = files.Length;
int fileCount = files.Length;
foreach (var file in files ...

Categories

Resources