Putting restrictions on deleting hashtable - c#

I have a hashtable in my forms. So basically I have 2 button Add and Delete. When I put info in the textbox and add it adds it in the hashtable. But when I click delete it deletes it and when there's no value in it, it shows an error.
Question: So what I want to do is that when I put info in textBox1 which is not added in the Hashtable, it should give an error otherwise if the value is already added, it should just delete it.
public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "" && b == "" || a == "" || b == "")
{
MessageBox.Show("Missing Input!");
}
else
{
MessageBox.Show("Added successfully");
label4.Text = a + " " + b;
}
}
private void button4_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(a)) // but this deletes it even if the value has not been added
{
MessageBox.Show(textBox1.Text + "has been removed");
Info.Remove(a);
}
}
For example: If I add 2 in Hashtable and try to delete 3, it will still delete it just because there's some value in the textBox.

public Form1()
{
InitializeComponent();
}
Hashtable Info = new Hashtable();
private void AddToHashTable_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "" || b == "")
{
MessageBox.Show("Missing Input!");
}
else if(Info.ContainsKey(a) || Info.ContainsKey(b))
{
MessageBox.Show("Hash table already contain this key");
}
else
{
Info.Add(a);
Info.Add(b);
MessageBox.Show("Added successfully");
label4.Text = a + " " + b;
}
}
private void DeleteFromHashTable_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
string b = textBox2.Text;
if (a == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(a)) // but this deletes it even if the value has not been added
{
MessageBox.Show(a + " has been removed");
Info.Remove(a);
}
else
{
MessageBox.Show(a + " is not part of the hash table");
}
//same check here for b
if (b == "")
{
MessageBox.Show("Missing Value");
}
else if(Info.ContainsKey(b)) // but this deletes it even if the value has not been added
{
MessageBox.Show(b + " has been removed");
Info.Remove(b);
}
else
{
MessageBox.Show(b + " is not part of the hash table");
}
}
I change the code a little bit. You miss some crucial things. Like check if the keys are already exist in the HashTable when you try to add them. If you try to add existing key exception will occur. Also I changed name of the methods, you miss to add the both text boxes in the hash table.

Related

Why am I receiving an System.InvalidCastException when I am trying to call my ShowStatement method?

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;
}
...

Adding a new line when checking a checkbox

When I click on a checkbox I want the next checkbox information to be displayed on a new line, I know how to do this with "\r\n" however when unchecking the box and rechecking the box, it adds a new line above the text moving the original text down by 1 line. https://imgur.com/a/IHDDG85
I've tried "\r\n" and Environment.NewLine
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
if (chkHamburger.Checked == true)
{
txtHamburger.Enabled = true;
txtHamburger.Text = "";
txtHamburger.Focus();
txtOrder.Text += ("Hamburger");
}
else
{
txtHamburger.Enabled = false;
txtHamburger.Text = "0";
}
if (chkHamburger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Hamburger", "");
}
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
if (chkCheeseBurger.Checked == true)
{
txtCheeseBurger.Enabled = true;
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
txtOrder.Text += ("Cheese Burger");
}
else
{
txtCheeseBurger.Enabled = false;
txtCheeseBurger.Text = "0";
}
if (chkCheeseBurger.Checked == false)
{
txtOrder.Text = txtOrder.Text.Replace("Cheese Burger", "");
}
}
I want the text of a checkbox to be displayed on a new line but when rechecking the box a whitespace should not appear above it.
I suggest you to use a List<string> where you add or remove your orders. Then it is easy to rebuild the txtOrder data with a single line of code using string.Join
List<string> orders = new List<string>();
private void chkHamburger_CheckedChanged(object sender, EventArgs e)
{
txtHamburger.Enabled = chkHamburger.Checked;
if (chkHamburger.Checked)
{
txtHamburger.Text = "";
txtHamburger.Focus();
orders.Add("Hamburger");
}
else
{
txtHamburger.Text = "0";
orders.Remove("Hamburger");
}
UpdateOrders();
}
private void chkCheeseBurger_CheckedChanged(object sender, EventArgs e)
{
txtCheeseBurger.Enabled = chkCheeseBurger.Checked;
if (chkCheeseBurger.Checked)
{
txtCheeseBurger.Text = "";
txtCheeseBurger.Focus();
orders.Add("Cheese Burger");
}
else
{
txtCheeseBurger.Text = "0";
orders.Remove("Cheese Burger");
}
UpdateOrders();
}
private void UpdateOrders()
{
txtOrders.Text = string.Join(Environment.NewLine, orders);
}
The best way to do this is to have a routine that builds the contents of the text independent of what just happened -- this you could use join or a loop to create the text contents.
Make this a function and call it when the check boxes change. The function loops over all your items and adds them to the output with the formatting and totals etc.

Enabled/Disabled Button based on User Permission [C# MySQL]

I'm trying with some code to disable/enable button based on user permission.
However, the code seem like nothing change to the system.
Anyone can advice/guide me on these? Thanks in advance.
public partial class frmTest : Form
{
public string UserID;}
private void frmTest_Load(object sender, EventArgs e)
{
RefreshActivate();
private void RefreshActivate()
{
DataSet ds = new DataSet();
MySQLClass.query(ds, "SELECT * FROM users WHERE username = '" + UserID + "'");
string strPermission = ds.Tables[0].Columns["permission"].ToString();
if (strPermission == "Admin")
{
btnActivate.Enabled = true;
}
else if (strPermission == "ReadOnly")
{
btnActivate.Enabled = false;
}
else
{
btnActivate.Enabled = false;
}
}}
Picture: https://i.stack.imgur.com/BevH8.png
Try to check first the permission if not null
if(!strPermission.Equals(null)//or ""
{
if (strPermission == "Admin")
{
btnActivate.Enabled = true;
}
else if (strPermission == "ReadOnly")
{
btnActivate.Enabled = false;
}
}else{
//value of permision is empty
MessageBox.Show("Permission is empty");
}
Now if the permission is empty it is something to do or fix when retrieving the data

Removing text when onSelectedChange Occurs

I am just wondering if anyone could give me indication as to how to remove a piece of text if a statement is not satisfied after onSelectedChange event.
My code,
protected void currency_SelectedIndexChanged(object sender, EventArgs e)
{
if (stm_currency.SelectedItem != null)
{
lblResults.Text = "" +
stm_merchant.SelectedItem.Text + " statement for " +
stm_month.SelectedItem.Text + " " +
stm_year.SelectedItem.Text;
}
else
{
lblResults.Text.Remove(0);
}
}
change this line of code
lblResults.Text = "";
It would set it to be an empty string.
The remove method returns a new string in which a specified number of characters in the current instance beginning at a specified position have been deleted.
http://msdn.microsoft.com/en-us/library/d8d7z2kk(v=vs.110).aspx
You should use lblResults.Text = ""; or lblResults.Text = string.Empty;
You should check to see if the label needs invoked first.
delegate void setLabelText(string s);
public void invokeSetLabelText(string s)
{
if (this.lblResults.InvokeRequired)
{
setLabelText d = new setLabelText(invokeSetLabelText);
this.Invoke(d, new object[] { s });
}
else
lblResults.Text = s;
}
protected void currency_SelectedIndexChanged(object sender, EventArgs e)
{
if (stm_currency.SelectedItem != null)
invokeSetLabelText(string.Format("{0} statement for {1} {2}",
stm_merchant.SelectedItem.Text,
stm_month.SelectedItem.Text,
stm_year.SelectedItem.Text));
else
invokeSetLabelText(string.Empty);
}

how to run multiple background process in a button

I am having a problem. I am new in c#. In this code when I click the button2, it will run bgutures.RunWorkerAsync(); only. But I need to modify it such like if I click on button2, all items the checkedListBox1.allitems contains are download, one by one in bgworker. Can anyone please help in this.
My code is :
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
string DayAtoZ = " ";
string DayDead = " ";
string Dayutures = " ";
string Daysify = " ";
string Dayfx = " ";
if (checkedListBox1.SelectedItem == "")
{
}
else if (checkedListBox1.SelectedItem == Dayutures)
{
}
else if (checkedListBox1.SelectedItem == DayAtoZ)
{
}
else if (checkedListBox1.SelectedItem == Daysify)
{
}
else if (checkedListBox1.SelectedItem == DayDead)
{
}
else if (checkedListBox1.SelectedItem == Dayfx)
{
}
{
bgutures.RunWorkerAsync();
}
{
bgDead.RunWorkerAsync();
}
{
bgsify.RunWorkerAsync();
}
{
bgAtoZ.RunWorkerAsync();
}
{
}
}
Instead of one BackgoundWorker use as many as your need.
if (checkedListBox1.SelectedItem == "")
{
var worker = new BackgroundWorker();
.. do setup
worker.RunWorkerAsync();
}
else if (checkedListBox1.SelectedItem == Dayutures)
{
var worker = new BackgroundWorker();
.. do setup
worker.RunWorkerAsync();
}

Categories

Resources