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;
Related
I created a little program to create a log file to record people's ID number, so far it runs good, no issues or errors, but recently I notice after running for three days it froze another program, until I force closed it. Can anyone take a look to the code to see if there is anything is wrong with it or to improve the code. Thank you.
The programs works with .NET Frameworks 3.5 and is for a Windows XP system, if is possible to make it work with a lower .NET Framework to reduce the installation of additional files.
MainWin form creates a fullscreen window to mask/cover some elements from other software. Is set as topmost to be always be on the top of everything. It has a transparent section with in a text file, then it minimize the window and finally activates a timer. When the timer finish, its maximaze the window again. It has a button to open the LoginWin form and a button to clear the data from the serieBox and return the cursor to the textbox.
LoginWin form is a window to input login information to open the LogFileWin form.
LogFileWin form is a window to read the saved data from the text file in a richTextBox, this data is from the MainWin form. It has a close button and a button to open FolderBrowserDialog to save the text file in another location or to a removable storage device.
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;
namespace LogSerie
{
public partial class MainWin : Form
{
public MainWin()
{
InitializeComponent();
}
private void MainWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void serieBox_KeyDown(object sender, KeyEventArgs e)
{
this.serieBox.MaxLength = 10;
if (e.KeyCode == Keys.Enter)
{
if ((serieBox.Text != ""))
{
if (serieBox.Text == "WLMANTO")
{
StreamWriter B = new StreamWriter("LogfileOperator.txt", true);
B.WriteLine(DateTime.Now + " " + label1.Text + " " + serieBox.Text);
B.Close();
serieBox.Clear();
this.WindowState = FormWindowState.Minimized;
timerManto.Enabled = true;
}
else
{
StreamWriter A = new StreamWriter("LogfileOperator.txt", true);
A.WriteLine(DateTime.Now + " " + label1.Text + " " + serieBox.Text);
A.Close();
serieBox.Clear();
this.WindowState = FormWindowState.Minimized;
timerOperador.Enabled = true;
}
}
}
}
private void timerOperador_Tick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
timerOperador.Enabled = false;
}
private void timerManto_Tick(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
timerManto.Enabled = false;
}
private void logButton_Click(object sender, EventArgs e)
{
LoginWin openForm = new LoginWin();
openForm.ShowDialog();
}
private void borrarBut_Click(object sender, EventArgs e)
{
serieBox.Clear();
serieBox.Select();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace LogSerie
{
public partial class LoginWin : Form
{
public LoginWin()
{
InitializeComponent();
}
private void LoginWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void entrarBut_Click(object sender, EventArgs e)
{
if ((usuBox.Text != "") && (contraBox.Text != ""))
{
if ((usuBox.Text == "ADMIN") && (contraBox.Text == "PASS"))
{
LogFileWin openForm = new LogFileWin();
openForm.TopMost = true;
openForm.ShowDialog();
usuBox.Clear();
contraBox.Clear();
this.Close();
}
else
{
MessageBox.Show("Login Incorrect", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
private void cancelBut_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace LogSerie
{
public partial class LogFileWin : Form
{
public LogFileWin()
{
InitializeComponent();
}
private void LogFileWin_Load(object sender, EventArgs e)
{
this.TopMost = true;
}
private void logfileButton_Click(object sender, EventArgs e)
{
string path = #"C:\LogfileOperator\LogfileOperator.txt";
StreamReader stream = new StreamReader(path);
string filedata = stream.ReadToEnd();
richTextBox1.Text = filedata.ToString();
stream.Close();
}
private void closeBut_Click(object sender, EventArgs e)
{
this.Close();
}
private void usbBut_Click(object sender, EventArgs e)
{
string fileName = "LogfileOperator.txt";
string sourcePath = #"C:\LogfileOperator";
using (FolderBrowserDialog ofd = new FolderBrowserDialog())
{
if (ofd.ShowDialog() == DialogResult.OK)
{
FileInfo fileInfo = new FileInfo(fileName);
sourcePath = Path.Combine(ofd.SelectedPath, fileInfo.Name);
File.Copy(fileName, sourcePath, true);
MessageBox.Show("Logfile Saved", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
}
If you're forced to use this old OS and old framework, you're going to have weird bugs like this. You can maybe work around it by reducing resource usage.
You're constantly creating new copies of your forms LoginWin and LogFileWin, which require OS resources. Instead create one instance of each form and re-use them.
There's also not any exception handling in your code, so you could have problems if files don't exist, or permissions change, or all sort of things. You need to have exception handling and that will give you more information about problems when they occur.
To re-use a form, create an instance as a private field in your class:
public partial class LoginWin : Form
{
// store the LogFileWin form so that we can re-use it
private LogFileWin _logFileWin;
public LoginWin()
{
InitializeComponent();
_logFileWin = new LogFileWin(); { TopMost = true; }
}
private void LoginWin_Load(object s, EventArgs e) { TopMost = true; }
private void entrarBut_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(usuBox.Text) ||
string.IsNullOrEmpty(contraBox.Text))
{
return;
}
if ((usuBox.Text == "ADMIN") &&
(contraBox.Text == "PASS"))
{
// add a reset function to the form
// that makes it ready to display again
_logFileWin.Reset();
// show the dialog
_logFileWin.ShowDialog();
usuBox.Clear();
contraBox.Clear();
this.Close();
}
else
{
MessageBox.Show("Login Incorrect",
"Message",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
private void cancelBut_Click(object s, EventArgs e) { Close(); }
}
For exception handling:
public partial class LogFileWin : Form
{
public LogFileWin()
{
InitializeComponent();
}
private void LogFileWin_Load(object s, EventArgs e) { TopMost = true; }
// new function to reset the the dialog to be shown again
public void Reset() { richTextBox1.Text = string.Empty; }
private void logfileButton_Click(object s, EventArgs e)
{
var path = #"C:\LogfileOperator\LogfileOperator.txt";
try
{
// reading from a file can fail, so this
// needs to be wrapped in a try catch
using (var stream = new StreamReader(path))
{
richTextBox1.Text = stream.ReadToEnd();
}
}
catch (Exception ex)
{
var m = String.Format("Unable to read '{0}'; {1}",
path, ex.Message);
MessageBox.Show(message,
"File read error",
MessageBoxButtons.Ok,
MessageBoxIcon.Error);
}
}
private void closeBut_Click(object s, EventArgs e) { this.Close(); }
// we can re-use the folder browser dialog;
// don't need to create a new one every time
FolderBrowserDialog _ofd = new FolderBrowserDialog();
private void usbBut_Click(object sender, EventArgs e)
{
var sourceFileName = "LogfileOperator.txt";
var destFolder = #"C:\LogfileOperator";
var destFileName = string.Empty;
try
{
if (_ofd.ShowDialog() == DialogResult.OK)
{
destFileName = Path.Combine(_ofd.SelectedPath,
sourceFileName);
// every time you do anything with a
// file, it needs to be in a try/catch
// in case the file doesn't exist,
// or the user doesn't have permission.
File.Copy(sourceFileName, destFileName, true);
MessageBox.Show("Logfile Saved",
"Message",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
// show a message to the user informing them
// of the error and why it occurred.
var m = string.Format("Copy '{0}' to '{1}' failed; {2}",
sourceFileName,
destFileName,
ex.Message);
MessageBox.Show(m,
"File copy error",
MessageBoxButtons.Ok,
MessageBoxIcon.Error);
}
}
}
I have a program where a user fills in a form and hits calculate, then when the user hits summary it will show all the users that have entered in data. When more users enter data, they are simply added to the summary using the same lbl (lblUsers) the only problem I am having is being able to delete the most recent entry into the summary which would be the newest made label.
using System;
using System.Collections;
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;
namespace LifeInsurance
{
public partial class frmMain : Form
{
double commissionRate;
double insuranceAmount;
double totalAmount;
int numberOfCustomers;
double totalInsuranceDollars;
double totalCommission;
private void btnClearAll_Click(object sender, EventArgs e)
{
lblUsers.Text = "";
}
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
}
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
string firstName = txtFirstName.Text;
string lastName = txtLastName.Text;
insuranceAmount = int.Parse(txtInsuranceAmount.Text);
}catch (Exception)
{
MessageBox.Show("You must enter all details");
}
if(insuranceAmount>= 1000)
{
commissionRate = 0.005;
totalAmount = insuranceAmount * 0.005;
}
if (insuranceAmount >= 100000)
{
commissionRate = 0.0010;
totalAmount = insuranceAmount * 0.0010;
}
if (insuranceAmount >= 1000000)
{
commissionRate = 0.0015;
totalAmount = insuranceAmount * 0.0015;
}
totalInsuranceDollars += totalAmount;
totalCommission += commissionRate;
numberOfCustomers += 1;
lblUsers.Text += "Name: "+txtFirstName.Text +" "+ txtLastName.Text+"
"+ "Payout Amount: "+totalAmount+Environment.NewLine;
lblUsers.Text += "Total Policies: " + numberOfCustomers+" " + "Total
Insurance Dollars Earned: " + totalInsuranceDollars+" " + "Total
Commission Earned: " + totalCommission+Environment.NewLine;
}
private void btnSummary_Click(object sender, EventArgs e)
{
lblUsers.Visible = true ;
}
private void btnClear_Click(object sender, EventArgs e)
{
//remove one label
}
}
}
I'm sorry, if I understand correctly you want your Label to show all but the last entry when the user clicks "Summary" is that correct? So in your screenshot it shows 3 entries, but you want only 2 entries to be shown?
If so, see if this helps:
public static void btnSummary_Click(object sender, EventArgs e)
{
string currentText = lblUsers.Text;
int positionOfLastEntry = currentText.LastIndexOf("Name:");
string textWithoutLastEntry = currentText.Substring(0, positionOfLastEntry);
lblUsers.Text = textWithoutLastEntry;
lblUsers.Visible = true;
}
I got an error which i cant fix:
Error 1 'System.Windows.Forms.Label' does not contain a definition for 'Copy'
and no extension method 'Copy' accepting a first argument of
type'System.Windows.Forms.Label'
could be found (are you missing a using directive or an assembly reference?)
//path 156 22 FileWatcherEigen
That was my error. Can someone help me and explain to me what went wrong?
This is my code:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private bool pause = false;
private bool cut1 = false;
private bool copy1 = false;
public Form1()
{
InitializeComponent();
}
// The lines with performed actions of a file
private void fileSystemWatcher1_Created(object sender,System.IO.FileSystemEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Created> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Changed> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
private void fileSystemWatcher1_Deleted(object sender, System.IO.FileSystemEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Deleted> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
private void fileSystemWatcher1_Renamed(object sender, System.IO.RenamedEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Renamed> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
private void fileSystemWatcher2_Changed(object sender, System.IO.FileSystemEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Changed> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
private void fileSystemWatcher2_Created(object sender, System.IO.FileSystemEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Created> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
private void fileSystemWatcher2_Deleted(object sender, System.IO.FileSystemEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Deleted> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
private void fileSystemWatcher2_Renamed(object sender, System.IO.RenamedEventArgs e)
{
if (!pause)
{
listBox1.Items.Add("File Renamed> " + e.FullPath + " -Date:" + DateTime.Now);
}
}
//1st directory
private void button2_Click(object sender, EventArgs e)
{
if (dlgOpenDir.ShowDialog() == DialogResult.OK)
{
fileSystemWatcher1.EnableRaisingEvents = false; // Stop watching
fileSystemWatcher1.IncludeSubdirectories = true;
fileSystemWatcher1.Path = dlgOpenDir.SelectedPath;
textBox1.Text = dlgOpenDir.SelectedPath; // Text of textBox2 = Path of fileSystemWatcher2
fileSystemWatcher1.EnableRaisingEvents = true; // Begin watching
}
}
//2nd directory
private void button3_Click(object sender, EventArgs e)
{
if (dlgOpenDir.ShowDialog() == DialogResult.OK)
{
fileSystemWatcher2.EnableRaisingEvents = false; // Stop watching
fileSystemWatcher2.IncludeSubdirectories = true;
fileSystemWatcher2.Path = dlgOpenDir.SelectedPath;
textBox2.Text = dlgOpenDir.SelectedPath; // Text of textBox2 = Path of fileSystemWatcher2
fileSystemWatcher2.EnableRaisingEvents = true; // Begin watching
}
}
//log
private void button1_Click(object sender, EventArgs e)
{
DialogResult resDialog = dlgSaveFile.ShowDialog();
if (resDialog.ToString() == "OK")
{
FileInfo fi = new FileInfo(dlgSaveFile.FileName);
StreamWriter sw = fi.CreateText();
foreach (string sItem in listBox1.Items)
{
sw.WriteLine(sItem);
}
sw.Close();
}
}
//pause watching
private void pause_button_Click(object sender, EventArgs e)
{
if (!pause)
{
pause = true;
pause_button.Text = "Unpause";
}
else
{
pause = false;
pause_button.Text = "Pause Watching";
}
}
//clear listbox
private void clear_button_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
private void Transfer_Click(object sender, EventArgs e)
{
if (copy1)
{
File.Copy(FileBrowseBox.Text, Path.Combine(DestinationBox.Text, Path.ChangeExtension(FileNameBox.Text, Path.GetExtension(FileBrowseBox.Text))));
}
}
private void Browse_file_Click(object sender, EventArgs e)
{
DialogResult resDialog = openFileDialog1.ShowDialog();
if (resDialog == DialogResult.OK)
{
FileBrowseBox.Text = openFileDialog1.FileName;
}
}
private void Browse_destination_Click(object sender, EventArgs e)
{
DialogResult resDialog = folderBrowserDialog1.ShowDialog();
if (resDialog == DialogResult.OK)
{
DestinationBox.Text = folderBrowserDialog1.SelectedPath;
}
}
private void CopyButton_CheckedChanged(object sender, EventArgs e)
{
copy1 = true;
}
}
}
It says the problem is within this part:
File.Copy(FileBrowseBox.Text, Path.Combine(DestinationBox.Text, Path.ChangeExtension(FileNameBox.Text, Path.GetExtension(FileBrowseBox.Text))));
I have tried to find it on this forum but i couldn't really find the answer or solution
It does work with this code:
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private bool cut = false;
private bool copy = false;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
File.Copy(FileBrowseBox.Text, Path.Combine(DestinationBox.Text, Path.ChangeExtension(FileBox.Text, Path.GetExtension(FileBrowseBox.Text))));
label2.Text = "File Transfer Succeeded";
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult resDialog = openFileDialog1.ShowDialog();
if (resDialog == DialogResult.OK)
{
FileBrowseBox.Text = openFileDialog1.FileName;
label2.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
DialogResult resDialog = folderBrowserDialog1.ShowDialog();
if (resDialog == DialogResult.OK)
{
DestinationBox.Text = folderBrowserDialog1.SelectedPath;
label2.Text = "";
}
}
private void radioButton1_CheckedChanged(object sender, EventArgs e)
{
copy = true;
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
cut = true;
}
}
}
You're getting this error because you have a label named File on your form that's being referenced rather than System.IO.File. You can either rename the Label, which I'd recommend, or you can use the fully qualified path of System.IO.File.Copy instead.
Apparently you have a Label named File. It shadows the System.IO.File class and causes the error. Specifying full class name should eliminate the problem:
System.IO.File.Copy(...
Ok I got this annoying error today and “a” DID contain a definition for “b”.
I got into this mess after opening the solution in VS2012 and then opening it VS2010.
Turns out by deleting the reference DLL in the affected project, building the reference DLL project, then re-referencing allowed VS to see the definition.
Just to note. I have got similar error while debugging, after I have renamed property in the class. Checked everything, even searched for old property name witch ctrl+shift+f5 in all solution. Nothing found...
After a while I noticed existing breakpoint with 'When hit...' condition to output value of the old property.
There is one other simple case where this will happen. Lets say you add a tool such as a "Button" to your form. Once you double click the tool,(in Visual Studio) the code private void button1_Click(object sender, EventArgs e) { } will be created in your Form1.cs. The code this.button1.Click += new System.EventHandler(this.button1_Click); will also be created in your Form1.Designer.cs. If you deleted the first set of code(for what ever reason) then you will also need to delete the second bit of code or else you will get this error. This may be a specific/simple situation but this is a error that newer programmers might run into.
I have this code in a new Form where i add text to a textBox and then it's added to the listBox as item:
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;
namespace GatherLinks
{
public partial class ChangeLink : Form
{
public ChangeLink()
{
InitializeComponent();
}
public string getText()
{
return textBox1.Text;
}
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
DialogResult = DialogResult.OK;
}
else
{
}
}
private void ChangeLink_Load(object sender, EventArgs e)
{
this.AcceptButton = button1;
}
}
}
And this is how i add the text to the listBox:
private void button2_Click(object sender, EventArgs e)
{
cl = new ChangeLink();
cl.StartPosition = FormStartPosition.CenterParent;
DialogResult dr = cl.ShowDialog(this);
if (dr == DialogResult.Cancel)
{
cl.Close();
}
else if (dr == DialogResult.OK)
{
label4.Text = cl.getText();
mainUrl = cl.getText();
if (!LocalyKeyWords.ContainsKey(mainUrl))
{
newUrl = true;
KeysValuesUpdate();
}
else
{
newUrl = false;
KeysValuesUpdate();
}
OptionsDB.set_changeWebSite(cl.getText());
cl.Close();
listBox1.SelectedIndex = listBox1.Items.Count - 1;
}
}
The problem is if the text was very long so in the right bound/border of the listBox the text of the item is cut. So to see it i want somehow to move it one line down or how much lines need to show the rest of the item text/name
So it will count as one item but if needed on some lines.
Update:
This is the part where i load the items to the listBox when im running my application:
private void ListBoxLoadKeys(Dictionary<string, List<string>> dictionary, string FileName)
{
int t = listBox1.Width;
using (StreamReader sr = new StreamReader(FileName))
{
while ((line = sr.ReadLine()) != null)
{
int i = line.Count();
tokens = line.Split(',');
dictionary.Add(tokens[0], tokens.Skip(1).ToList());
string tt = tokens[1].Substring(t - tokens[1].Length);
data.Add("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]);
}
}
listBox1.DataSource = data;
}
So variable t is the listBox Length(width)
And in this line i tried to calculate and get the text of tokens[1]"
string tt = tokens[1].Substring(t - tokens[1].Length);
But im getting an error startIndex cannot be larger than length of string
Now i know the listBox Length(Width) but i don't want to put the text tokens[1] in a new line only if it's out of the bound out of the listbox Width(Length)
How can i fix and do this ?
Updated again:
Changed the code again now im trying first to check if each line in the variable data lngth is bigger then the variable t:
private void ListBoxLoadKeys(Dictionary<string, List<string>> dictionary, string FileName)
{
int t = listBox1.Width;
using (StreamReader sr = new StreamReader(FileName))
{
while ((line = sr.ReadLine()) != null)
{
int i = line.Count();
tokens = line.Split(',');
dictionary.Add(tokens[0], tokens.Skip(1).ToList());
//string tt = tokens[1].Substring(t - tokens[1].Length);
data.Add("Url: " + tokens[0] + " --- " + "Localy KeyWord: " + tokens[1]);
if (data[i].Length > t)
{
MessageBox.Show("big");
}
}
}
listBox1.DataSource = data;
}
if (data[i].Length > t)
{
MessageBox.Show("big");
}
But im getting an error: Index was out of range. Must be non-negative and less than the size of the collection
You can't do this with a standard listbox. You need to create your own multi line listbox. See this link for some guidance. http://www.codeproject.com/Articles/2695/An-editable-multi-line-listbox-for-NET
I've implemented this at work (ignoring the author's poor choice of colour scheme), and it works fine.
I am having a very annoying issue that I have been looking everywhere to find but none of them make sense to me. I have only recently started C# so if its a silly mistake, well sorry.
Ive built a calculator and I can successfully make it but I want it to show the operations as the user clicks them. For example when the user clicks on the 6 button of course it shows 6 in the textfield then when he presses the plus(+) button, it should display [6 + ] and then he presses 5 for example and it looks like this in the textfield [6 + 5].
Now here's my error. I can make all the above work but when i click the equals(=) button, I get an error. It says
"Input string was not in correct format."
It says the error is on this line of code:
decimal total = Convert.ToDecimal(LCD.Tag) +
Convert.ToDecimal(LCD.Text);
Heres my code:
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;
namespace WindowsFormsApplication1
{
public partial class Window : Form
{
bool pluss = false;
bool minuss = false;
bool multiplyy = false;
bool dividee = false;
public Window()
{
InitializeComponent();
}
private void clear_Click(object sender, EventArgs e)
{
LCD.Text = "";
}
private void dec_Click(object sender, EventArgs e)
{
if (LCD.Text.Contains("."))
{
return;
}
else {
LCD.Text = LCD.Text + ".";
}
}
private void zero_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "0";
}
private void one_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "1";
}
private void two_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "2";
}
private void three_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "3";
}
private void four_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "4";
}
private void five_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "5";
}
private void six_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "6";
}
private void seven_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "7";
}
private void eight_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "8";
}
private void nine_Click(object sender, EventArgs e)
{
LCD.Text = LCD.Text + "9";
}
private void plus_Click(object sender, EventArgs e)
{
if (LCD.Text == "")
{
return;
}else{
pluss = true;
LCD.Tag = LCD.Text;
LCD.Text = LCD.Text + " + ";
}
}
private void equal_Click(object sender, EventArgs e)
{
decimal total = Convert.ToDecimal(LCD.Tag) + Convert.ToDecimal(LCD.Text);
LCD.Text = total.ToString();
}
}
}
I am awaiting someone's response and I'll be so greatful if I get a fix.
Thanks.
When your program crashes:
Break into the debugger.
Inspect the value of LCD.Tag and LCD.Text.
Viola, you will surely notice something awry in the format.
I realize this is a practice project, but this kind of string manipulation back and forth is not the best way to build a calculator. Better to separate the display from the data structures used to contain expression trees and values (i.e., the data structures used to do the actual calculation).
You're trying to convert a string that contains the "+" symbol to decimal format.
Place some breakpoints in your application and inspect where it crashes, the value will probably not be what you expect it to be.
Take a look at what you're giving to Convert.ToDecimal to convert (LCD.Text). It expects a number in string format but you're passing it something like "1 + 2" which is not. You must evaluate the expression yourself.