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.
Related
The goal is to display the text from user input using radio button and combo box. I'm using Visual Studio, by the way.
This is the code from the first window:
private void btn_apply_Click(object sender, EventArgs e)
{
firstName = tbx_firstName.Text;
middleName = tbx_middleName.Text;
lastName = tbx_lastName.Text;
completeName = firstName + " " + middleName + " " + lastName + " ";
gender = lbl_gender.Text;
level = lbl_level.Text;
status = lbl_status.Text;
if (rbtn_male.Checked)
{
lbl_gender.Text = rbtn_male.Text.ToUpper();
}
else
{
lbl_gender.Text = rbtn_female.Text.ToUpper();
}
//Level
if (rbtn_gradeEleven.Checked)
{
lbl_level.Text = rbtn_gradeEleven.Text.ToUpper();
}
else if (rbtn_gradeTwelve.Checked)
{
lbl_level.Text = rbtn_gradeTwelve.Text.ToUpper();
}
else if (rbtn_iST.Checked)
{
lbl_level.Text = rbtn_iST.Text.ToUpper();
}
else if (rbtn_iSM.Checked)
{
lbl_level.Text = rbtn_iSM.Text.ToUpper();
}
else
{
}
//Admission Status
cbx_status.SelectedItem.ToString();
//Form2
this.Hide();
Form2 output = new Form2();
output.Show();
Meanwhile, this is the code for the second window (Result):
private void Form2_Load(object sender, EventArgs e)
{
lbl_displayName.Text = Form1.completeName;
lbl_displayGender.Text = Form1.gender;
lbl_displayLevel.Text = Form1.level;
lbl_displayStatus.Text = Form1.status;
}
Thank you!
when Form2 should display elements from Form1, the former surely has to have a reference to the latter. So start giving Form2 a reference to your Form1-instance, e.g. using a constructor-arg on Form2.
However usually you don't want to pass controls or forms around, but just specific values within those. In your case those are the gender, name the level and the status. So just provide those arguments to Form2, not the entire Form1-instance:
class Form2 : Form
{
private readonly string name; // ...
public Form2(string name, string status, string level, string gender)
{
this.name = name;
// ...
}
}
Now you can easily access those variables within your Load-event:
private void Form2_Load(object sender, EventArgs e)
{
lbl_displayName.Text = this.name;
lbl_displayGender.Text = this.gender;
lbl_displayLevel.Text = this.level;
lbl_displayStatus.Text = this.status;
}
Change:
Form2 output = new Form2();
output.Show();
To:
Form2 output = new Form2();
output.Show(this); // <-- Form1 as the Owner of output
Now in Form2, simply cast .Owner back to Form1:
private void Form2_Load(object sender, EventArgs e)
{
Form1 f1 = (Form1)this.Owner;
lbl_displayName.Text = f1.completeName;
lbl_displayGender.Text = f1.gender;
lbl_displayLevel.Text = f1.level;
lbl_displayStatus.Text = f1.status;
}
I am able to add accounts of different types through another form to the list statements which I can then add to the list box lstaccounts. However, when I select an account in my list box and press the view statement button I get that exception on the 'lblBank.Text = ShowStatement((IStatement)lstAccounts.SelectedItem);' line... any idea why this could be happening?
public List<IStatement> statements;
private int accountCounter = 0;
private int statementsViewed = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
statements = new List<IStatement>();
}
private void btnView_Click(object sender, EventArgs e)
{
if (lstAccounts.SelectedIndex > -1)
{
lblBank.Text = ShowStatement((IStatement)lstAccounts.SelectedItem);
statementsViewed += 1;
lblTotal.Text = statementsViewed.ToString();
}
}
private string ShowStatement(IStatement item)
{
String msg = "Account Number: " + item.AccountNumber + "\n"
+ "Name: " + item.AccountName + "\n" + item.PrintStatement();
return msg;
}
private void btnAddAccount_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
if(form2.ShowDialog() == DialogResult.OK)
{
if (form2.txtValue.Text == "" && form2.txtMinMonthly.Text == "")
{
BankAccount b = form2.GetBankAccount();
statements.Add(b);
}
else if (form2.txtMinMonthly.Text == "")
{
InsurancePolicy i = form2.GetInsurancePolicy();
statements.Add(i);
}
else
{
PlatinumCurrent p = form2.GetPlatinumCurrent();
statements.Add(p);
}
foreach (IStatement os in statements)
{
lstAccounts.Items.Add(os.ToString());
accountCounter += 1;
}
}
}
The exact error I'm getting is: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'TelephoneBanking.IStatement'.'
You added it as .ToString() in your btnAddAccount_Click. Try add the item, not the item.ToString().
private void btnAddAccount_Click(object sender, EventArgs e)
{
...
foreach (IStatement os in statements)
{
lstAccounts.Items.Add(os); // ###### removed os.ToString() ######
accountCounter += 1;
}
...
The following code reads port data and writes the data into a textbox with timestemp once it differs from the previous one. Afterwards I can save the data to a textfile.
Instead of writing it into a textbox and then save it to text file per button, I would like it to auto append to the text file every x seconds (lets say 10). By reading through other questions I got some ideas but was not really able to execute them.
Anyone can help?
public partial class Form1 : Form
{
private SerialPort myport;
private DateTime datetime;
private string in_data;
private string in_data_old = "";
public Form1()
{
InitializeComponent();
}
private void start_btn_Click(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 9600;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open();
data_tb.Text = "";
}
catch(Exception ex) {
MessageBox.Show(ex.Message, "Error");
}
}
void myport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
in_data = myport.ReadLine();
if (in_data != in_data_old)
{
this.Invoke(new EventHandler(displaydata_event));
}
in_data_old = in_data;
}
private void displaydata_event(object sender, EventArgs e)
{
datetime = DateTime.Now;
string time = datetime.Year+ "." +datetime.Month+ "." + datetime.Day + " " + datetime.Hour+ ":" +datetime.Minute+ ":" +datetime.Second;
data_tb.AppendText(time + "\t\t\t\t\t" + in_data+"\n");
}
private void stop_btn_Click(object sender, EventArgs e)
{
try
{
myport.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message, "Error");
}
}
private void save_btn_Click(object sender, EventArgs e)
{
try
{
string pathfile = #"C:\Users\xy\Desktop\DATA\";
string filename = "light_data.txt";
System.IO.File.AppendAllText(pathfile + filename, data_tb.Text);
MessageBox.Show("Data has been saved to "+pathfile, "Save File");
}
catch(Exception ex3)
{
MessageBox.Show(ex3.Message, "Error");
}
}
}
Add a Timer , you can find it on the toolbox and you can set it's interval for any timer you would like and add your btn click functionality there example :
private void timer1_Tick(object sender, EventArgs e)
{
myport = new SerialPort();
myport.BaudRate = 9600;
myport.PortName = port_name_tb.Text;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.DataReceived += myport_DataReceived;
try
{
myport.Open();
data_tb.Text = "";
}
catch(Exception ex) {
MessageBox.Show(ex.Message, "Error");
}
}
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();
I have a program which is able to retrieve various registry values using C# codes which was compiled and created using VS 2010.
However the problem arises when I tried to display the results retrieved from the Windows Registry into a rich text box within a form.
The form only shows 1 line which is the last value in the Array that contains the results.
Please do give some advice on the codes. Thanks!
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 Microsoft.Win32;
namespace Syscrawl
{
public partial class FTK_Menu_Browsing_History : Form
{
public FTK_Menu_Browsing_History()
{
InitializeComponent();
}
private void buttonFileHistory_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_File_History mfh = new FTK_Menu_File_History();
mfh.ShowDialog();
this.Close();
}
private void buttonEncryptedFiles_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_Encrypted_Files mef = new FTK_Menu_Encrypted_Files();
mef.ShowDialog();
this.Close();
}
private void buttonRecentlyAccessedFiles_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_Recently_Accessed_Files mraf = new FTK_Menu_Recently_Accessed_Files();
mraf.ShowDialog();
this.Close();
}
private void buttonRegistryHistory_Click(object sender, EventArgs e)
{
this.Hide();
FTK_Menu_Registry_History mrh = new FTK_Menu_Registry_History();
mrh.ShowDialog();
this.Close();
}
private void buttonMainMenu_Click(object sender, EventArgs e)
{
this.Hide();
Menu m = new Menu();
m.ShowDialog();
this.Close();
}
private void buttonLogOut_Click(object sender, EventArgs e)
{
this.Hide();
Syscrawl_Login sl = new Syscrawl_Login();
sl.ShowDialog();
this.Close();
}
private void FTK_Menu_Browsing_History_Load(object sender, EventArgs e)
{
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey("Software\\Microsoft\\Internet Explorer\\TypedURLs",
false);
PrintKeys(rk);
rk.Close();
}
catch (Exception MyError)
{
richTextBoxBrowsing.Text="An error has occurred: " + MyError.Message;
}
}
void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
richTextBoxBrowsing.Text="Couldn't open the desired subkey.";
return;
}
richTextBoxBrowsing.Text = "Subkeys of " + rk.Name;
try
{
string[] valnames = rk.GetValueNames();
int i = 0;
foreach (string s in valnames)
{
string val = (string)rk.GetValue(valnames[i++]);
richTextBoxBrowsing.Text="-----------------------------------------------";
richTextBoxBrowsing.Text=s + " contains " + val;
}
}
catch (Exception MyError)
{
richTextBoxBrowsing.Text = "An errors has occurred: " + MyError.Message;
}
}
private void richTextBoxBrowsing_TextChanged(object sender, EventArgs e)
{
}
}
}
By saying:
richTextBoxBrowsing.Text=
in each iteration of your loop, you keep on overwriting the text. So only the last call to the Text property gets printed.
You need to set the richTextBoxBrowsing.TextMode property to multiline, and then instead call:
richTextBoxBrowsing.AppendText(s + " contains " + val + "\n");
Oh, and by the way, use: string val = rk.GetValue(s).ToString();
so you can remove the int i = 0; declaration
You should use richTextBoxBrowsing.AppendText(...)
You're changing the entire contents with each call, instead of appending to it:
richTextBoxBrowsing.Text=s + " contains " + val;
should be
richTextBoxBrowsing.AppendText(s+" contains " + val+Environment.NewLine);
Confirm that you set
richTextBoxBrowsing.TextMode to
MultiLine
Change richTextBoxBrowsing.Text+=s + " contains " + val; in foreach loop
Use Debug.WriteLine to debug return
value
I think your loop is not correct.
In _void PrintKeys()_ your Loop overwerites your RichTextBox.Text-Value try something like:
String temp = "-----------------------------------------------";
foreach (string s in valnames)
{
String val = (String)rk.GetValue(valnames[i++]);
temp=temp+s + " contains " + val;
}
RichTextBox.text = temp;