How do i update an access database witin c#? - c#

I have a withdrawal screen in my code that i when i withdraw money i want it to update the access database but my code only removes the amount of money off the database from within the program. Once the program is closed the database resets to its previous state.
My code for this screen
int moneyselected = 0;
Decimal balance = frmaccount.Balance;
public FrmTransaction()
{
InitializeComponent();
}
private void btnWithdraw_Click(object sender, EventArgs e)
{
if (moneyselected == 0)
{
MessageBox.Show("Select Amount");
}
else
{
if (moneyselected > balance)
{
MessageBox.Show("Not enough funds");
}
else
{
balance = balance - moneyselected;
OleDbCommandBuilder cb = new OleDbCommandBuilder(FrmLogin.da);
FrmLogin.da.Update(FrmLogin.ds1, "tblCustomers");
MessageBox.Show("Amount Withdrawn = " + moneyselected.ToString() + "\r\nBalance = " + balance.ToString());
}
}
}
private void btnWithdrawreceipt_Click(object sender, EventArgs e)
{
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
Form FrmLogin = new FrmLogin();
this.Hide();
FrmLogin.Show();
}
private void FrmTransaction_Load(object sender, EventArgs e)
{
}
private void rb10_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 10;
}
private void rb20_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 20;
}
private void rb30_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 30;
}
private void rb40_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 40;
}
private void rb50_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 50;
}
private void rb60_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 60;
}
private void rb70_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 70;
}
private void rb80_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 80;
}
private void rb90_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 90;
}
private void Cashamountbox_Enter(object sender, EventArgs e)
{
}
private void rb100_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 100;
}
private void rb150_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 150;
}
private void rb250_CheckedChanged(object sender, EventArgs e)
{
moneyselected = 250;
}
}>>LOGIN PAGE<<
}
namespace BANK_ATM_PROJECT
{
public partial class FrmLogin : Form
{
public FrmLogin()
{
InitializeComponent();
}
int failedAttempts = 0;
public static OleDbConnection con = new OleDbConnection();
string dbProvider;
string dbSource;
public static OleDbDataAdapter da;
public static DataSet ds1 = new DataSet();
string sql;
string pin;
int rownum = 0;
bool valid = false;
public static decimal balance = 0;
private void FrmLogin_Load(object sender, EventArgs e)
{
{
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;";
dbSource = "Data Source = 'D:\\bank11.accdb'";
con.ConnectionString = dbProvider + dbSource;
ds1 = new DataSet();
con.Open();
sql = " SELECT tblCustomers.* FROM tblCustomers";
da = new OleDbDataAdapter(sql, con);
rownum = da.Fill(ds1, "tblCustomers");
con.Close();
{
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
System.Environment.Exit(0);
this.Close();
}
private bool validate()
{
ds1 = new DataSet();
con.Open();
sql = "SELECT tblCustomers.* FROM tblCustomers WHERE ((tblCustomers.AccountNo) = '" + txtAccount.Text + "')";
da = new OleDbDataAdapter(sql, con);
rownum = da.Fill(ds1, "tblCustomers");
con.Close();
if (rownum != 1)
{
return false;
}
else
{
pin = ds1.Tables["tblCustomers"].Rows[0][4].ToString();
if (pin == txtPin.Text)
{
return true;
}
else
{
MessageBox.Show("INVALID PIN");
return false;
}
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
valid = validate();
if (!valid)
{
//Increment the number of failed attempts
failedAttempts += 1;
if (failedAttempts == 1)
MessageBox.Show("You Have 2 Attempts Left");
if (failedAttempts == 2)
MessageBox.Show("You Have 1 Attempt Left");
//If equal to 3
if (failedAttempts == 3)
MessageBox.Show("Card Retained");
{
}
}
else
{
valid = validate();
if (valid == true)
{
if (txtAccount.Text == "11111111" && txtPin.Text == "9999")
{
Frmmanager Manager = new Frmmanager();
this.Close();
Manager.Show();
}
else
{
frmaccount account = new frmaccount();
this.Close();
account.Show();
{
txtAccount.Clear();
txtPin.Clear();
valid = validate();
if (valid == true)
{
if (txtAccount.Text == "11111111" && txtPin.Text == "9999")
{
Frmmanager Manager = new Frmmanager();
this.Close();
Manager.Show();
}
else
{
frmaccount Account = new frmaccount();
this.Close();
account.Show();
{
txtAccount.Clear();
txtPin.Clear();
}
}
}
}
}
}
}
}
}
}
I though the
ds.update would have updated it but this only seems to work within the program
Any help or advice would be appreciated

I think the problerm is in the following code,Here you cretate a new instance of FrmLogin instead of refering to the current instance:
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
Form FrmLogin = new FrmLogin();
this.Hide();
FrmLogin.Show();
}
try the following:
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
FrmLogin obj = (FrmLogin)Application.OpenForms["FrmLogin"];
this.Hide();
obj.Show();
}
And generraly when you referring to FrmLogin is better to use obj as ref in order to be sure you referenning to current instance. So add this to the start of your code:
obj = (FrmLogin)Application.OpenForms["FrmLogin"];
And every ref to FrmLogin make it via obj

are you checking the database in debug folder or in your project solution ?
try checking in debug folder.

Related

simple adding up value in windows forms ASP.NET trough button not working

i have a problem where when i try to add a value trough the click_button event, the value will remain the same, could someone help me out with this?
int parallelgroepnummer = 0;
protected void Page_Load(object sender, EventArgs e)
{
CheckBox1.Checked = false;
checkparallel = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (checkparallel == true)
{
{
parallelgroepen.Add(parallelgroepnummer, "test");
parallelgroepnummer = parallelgroepnummer + 1;
ListBox1.Items.Add("parallele groep " + parallelgroepnummer);
}
}
else
{
ListBox1.Items.Add("notparallel");
}
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkparallel == false)
{
checkparallel = true;
}
else
{
checkparallel = false;
}
}
the answer always returns 1 here.
int parallelgroepnummer = 0;
change in:
private static int parallelgroepnummer = 0;

System.FormatException: 'The format of the input string is incorrect.'

I am new with C# and I built a very basic calculator that allows a user to enter two numbers into two textboxes and an operator via buttons. When the user clicks result, the calculator computes the result.
For getting user input, I have: firstnumber = Double.Parse(fnum.Text);. The program compiles but throws the exception System.FormatException: 'The format of the input string is incorrect.'.
I have also tried firstnumber = Convert.ToDouble(fnum.Text); but got the same exception.
Here is my code:
namespace Bear3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private double firstnumber;
private double secondnumber;
private double resultt=0;
private bool plusch = false;
private bool minusch = false;
private bool multiplicationch = false;
private bool divisionch = false;
private void Button1_Click(object sender, EventArgs e)
{
Operator.Text="+";
plusch = true;
}
private void Label1_Click(object sender, EventArgs e)
{
}
private void Fnum_TextChanged(object sender, EventArgs e)
{
firstnumber = Convert.ToDouble(fnum.Text);
}
private void Label2_Click(object sender, EventArgs e)
{
}
private void Minus_Click(object sender, EventArgs e)
{
Operator.Text = "-";
minusch = true;
}
private void Multiplication_Click(object sender, EventArgs e)
{
Operator.Text = "*";
multiplicationch = true;
}
private void Division_Click(object sender, EventArgs e)
{
Operator.Text = "/";
divisionch = true;
}
private void Result_Click(object sender, EventArgs e)
{
if (plusch == true)
{
resultt = firstnumber + secondnumber;
}
else if (minusch == true)
{
resultt = firstnumber - secondnumber;
}
else if (multiplicationch == true)
{
resultt = firstnumber * secondnumber;
}
else if (divisionch == true)
{
resultt = firstnumber / secondnumber;
}
ResultShow.Text = Convert.ToString(resultt);
}
private void Snum_TextChanged(object sender, EventArgs e)
{
secondnumber = Double.Parse(snum.Text);
}
private void Clear_Click(object sender, EventArgs e)
{
plusch = false;
minusch = false;
multiplicationch = false;
divisionch = false;
ResultShow.Text = "";
Operator.Text = "";
fnum.Text = "";
snum.Text = "";
}
}
}
Rather than getting the variables on TextChanged which can fire more often than you expect, do it on the Result click action.
Move these lines to the top of the Result_Click and remove them from their current spot.
firstnumber = Convert.ToDouble(fnum.Text);
secondnumber =Convert.ToDouble(snum.Text);
I do recommend you check to see if the data is actually a Double so you don't get an error.
Update your Fnum_TextChanged and Snum_TextChanged methods to validate the text when parsing:
private void Fnum_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(fnum.Text))
{
if (double.TryParse(fnum.Text, out firstnumber) == false){
// notify user in message box or throw error
}
}
}
After this runs, if there is no error that means fnum.Text parsed and is now stored in your firstnumber variable.

How append Rx data on textBox?

I trying to do an inteface to monitoring the Serial Port. I am using Visual forms. So, I had created a combobox to select the PortCOM, a TextBox to send the data to Serial Port and a TextBoxReceber to receive the Serial Data. I trying print the data received in the TextBoxReceber, I'm using the AppendText but I haven't sucess. Anybody can help me?
My Form1.cs is:
namespace ConsoleESP
{
public partial class Form1 : Form
{
string RxString = "";
public Form1()
{
InitializeComponent();
timerCOM.Enabled = true;
atualizaCOMs();
}
private void atualizaCOMs()
{
int i = 0;
bool quantDif = false;
if (comboBox1.Items.Count == SerialPort.GetPortNames().Length)
{
foreach (string s in SerialPort.GetPortNames())
{
if (comboBox1.Items[i++].Equals(s) == false)
{
quantDif = true;
}
}
}
else quantDif = true;
if (quantDif == false) return;
comboBox1.Items.Clear();
foreach(string s in SerialPort.GetPortNames())
{
comboBox1.Items.Add(s);
}
comboBox1.SelectedIndex = 0;
}
private void timerCOM_Tick(object sender, EventArgs e)
{
atualizaCOMs();
}
private void btConnect_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen == false)
{
try
{
serialPort1.PortName = comboBox1.Items[comboBox1.SelectedIndex].ToString();
serialPort1.Open();
}
catch
{
return;
}
if (serialPort1.IsOpen)
{
btConnect.Text = "Desconectar";
comboBox1.Enabled = false;
}
}
else
{
try
{
serialPort1.Close();
comboBox1.Enabled = true;
btConnect.Text = "Conectar";
}
catch
{
return;
}
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if (serialPort1.IsOpen == true) serialPort1.Close();
}
private void btEnviar_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen == true)
serialPort1.Write(textBoxEnviar.Text);
}
private delegate void RefreshTextBox();
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
RxString = serialPort1.ReadExisting();
this.Invoke(new EventHandler(TrataDadoRecebido));
}
private void TrataDadoRecebido(object sender, EventArgs e)
{
textBoxReceber.AppendText(RxString);
}
}
}

RS 485 not showing any result [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I am trying to get read data from rs 485 communication interface and write in the textbox but i am not getting the data from this code. I am working on water measurement and I am beginner in c#. I have seen similar question like this but unable to get the answer. The data format is like this. D014802,+000.042,+000.082,003680,+000805.66,+025.25,0193FA,0.99697,0000,B7C9
Help me out .
public partial class MainForm : Form
{
SerialPort aSerialPort;
InputRegister mobjGlobalform2;
Form3 mobjGlobalform3;
LoginForm AdminLogin = new LoginForm();
//Form6 softwareVersion = new Form6();
bool isUserMode = true;
public MainForm()
{
InitializeComponent();
getAvailablePorts();
}
private void btn_close_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
InputRegister mobjform2 = new InputRegister();
if (checkBox1.Checked)
{
mobjGlobalform2 = mobjform2;
mobjform2.Show();
if(isUserMode==true)
{
mobjform2.groupbox_form2Takuwa.Hide();
mobjform2.Height = 215;
mobjform2.Width = 575;
}
}
else
{
mobjGlobalform2.Close();
//mobjform2.Close();
}
}
private void checkBox2_CheckedChanged(object sender, EventArgs e)
{
Form3 mobjform3 = new Form3();
if (checkBox2.Checked)
{
mobjGlobalform3 = mobjform3;
mobjform3.Show();
if(isUserMode==true)
{
mobjform3.groupbx_form3takuwamode.Hide();
mobjform3.Height = 254;
mobjform3.Width = 407;
}
}
else
{
mobjGlobalform3.Close();
//mobjform2.Close();
}
}
private void timer1_Tick_1(object sender, EventArgs e)
{
label13.Text = DateTime.Now.ToString();
// splitContainer1.Panel2.Controls.Add(label13);
if(AdminLogin.isAdminMode)
{
lbl_AdminLogout.Show();
isUserMode = false;
}
}
private void btn_Clear_Click(object sender, EventArgs e)
{
txtbox_ShowData.Text = String.Empty; // clear the data from text box
}
private void MenuStrip_AdminLogin_Click(object sender, EventArgs e)
{
//Form5 mobjform5 = new Form5();
AdminLogin.Show();
}
private void lbl_AdminLogout_Click(object sender, EventArgs e)
{
AdminLogin.isAdminMode = false;
isUserMode = true;
lbl_AdminLogout.Hide();
MessageBox.Show("Logout Successful");
}
private void btn_SoftwareVersion_Click(object sender, EventArgs e)
{
//softwareVersion.Show();
Form6 Versionform6 = new Form6();
Versionform6.Height = 272;
Versionform6.Width = 507;
Versionform6.Show();
}
private void btn_connectaddress_Click(object sender, EventArgs e)
{
Setting addressconnectform6 = new Setting();
addressconnectform6.Show();
if(isUserMode == true)
{
addressconnectform6.groupbx_takuwaform7.Hide();
addressconnectform6.Height = 257;
addressconnectform6.Width = 657;
}
else
{
addressconnectform6.groupbx_takuwaform7.Show();
}
}
#region combox
// port show in combobox
private void getAvailablePorts()
{
string[] ports = SerialPort.GetPortNames();
cbbx_comport.Items.Clear();
foreach (string comport in ports)
{
cbbx_comport.Items.Add(comport);
}
}
#endregion
private void btn_Connect_Click(object sender, EventArgs e)
{
initializeSensor();
aSerialPort.DataReceived += new SerialDataReceivedEventHandler(Rs485DataReceivedEventHandler);
}
private void Rs485DataReceivedEventHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sData = sender as SerialPort;
string recvData = sData.ReadLine();
this.Invoke((MethodInvoker)delegate { DataReceived(recvData); });
}
private void initializeSensor()
{
aSerialPort = new SerialPort(cbbx_comport.Text);
aSerialPort.BaudRate = 38400;
aSerialPort.Parity = Parity.None;
aSerialPort.StopBits = StopBits.One;
aSerialPort.DataBits = 8;
if (aSerialPort.IsOpen == false)
{
try
{
aSerialPort.Open();
//aSerialPort.WriteLine("c"); //clear
//aSerialPort.WriteLine("o");
}
catch { }
}
}
private void DataReceived(string recvData)
{
txtbx_sensorData.Text = recvData;
}
You are instantiating a local variable, not the field.
Instead of
SerialPort aSerialPort = new SerialPort(cbbx_comport.Text);
Try
aSerialPort = new SerialPort(cbbx_comport.Text);

c# - Cannot convert from void to list

So, I got kind of stuck over my head while I tried to program something new.
I'm trying to add objectBeer_pluche or objectBeer_Elektro to my OBJberenlijst on the Beren Main form from the details Form, so I can add both instances of 2 classes to the same list.
I'm not even sure this is possible by the way. So, I would like feedback if what I am trying to do is possible to start with. I already figured VOID is not right but I am really clueless here.
This is my main beren.cs form with an OBJberenlist, that's where I try to add objectBeer_pluche or objectBeer_Elektro into it:
public partial class Beren : Form
{
public interface Berenlijst { }
public List<Berenlijst> OBJberenLijst = new List<Berenlijst>();
public Beren()
{
InitializeComponent();
}
private void Beren_Load(object sender, EventArgs e)
{
}
private void BTNToevoegen_Click(object sender, EventArgs e)
{
this.Hide();
Details Details = new Details();
if (Details.ShowDialog(this) == DialogResult.OK)
{
OBJberenLijst.Add(Details.getdetails());
}
Details.Close();
Details.Dispose();
}
public void LijstLaden()
{
foreach(Beer berenobject in OBJberenLijst)
{
LST_beren.Items.Add(berenobject.Naam);
}
}
}
}
from this form called details.cs
public partial class Details : Form
{
public Details()
{
InitializeComponent();
BTN_toevoegen.DialogResult = DialogResult.OK;
BTN_cancel.DialogResult = DialogResult.Cancel;
}
private void Details_Load(object sender, EventArgs e)
{
RDB_pluche.Checked = true;
BTN_ok.Enabled = false;
}
private void RDB_pluche_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = true;
PANEL_elektro.Visible = false;
}
private void RDB_elektro_CheckedChanged(object sender, EventArgs e)
{
PANEL_pluche.Visible = false;
PANEL_elektro.Visible = true;
}
private void BTN_toevoegen_Click(object sender, EventArgs e)
{
open_foto.Filter = "jpg (*.jpg)|*.jpg|bmp(*.bmp)|*.bmp|png(*.png)|*.png";
if (open_foto.ShowDialog() == System.Windows.Forms.DialogResult.OK && open_foto.FileName.Length > 0)
{
TXT_adres.Text = open_foto.FileName;
PIC_beer.Image = Image.FromFile(open_foto.FileName);
}
}
private void BTN_ok_Click(object sender, EventArgs e)
{
}
public void getdetails()
{
if (RDB_pluche.Enabled == true)
{
Pluche_Beer objectBeer_pluche = new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
else
{
Elektronische_Beer objectBeer_Elektro = new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
}
private void Details_MouseMove(object sender, MouseEventArgs e)
{
foreach (Control c in this.Controls)
{
if (c is TextBox)
{
TextBox textBox = c as TextBox;
if (textBox.Text != string.Empty)
{
BTN_ok.Enabled = true;
}
}
}
}
}
}
The problem is between this line...
OBJberenLijst.Add(Details.getdetails());
...and this line.
public void getdetails()
List.Add() requires an object to add, but getdetails() returns void. You probably want to change getdetails() to something like the following:
public Berenlijst getdetails()
{
if (RDB_pluche.Enabled == true)
{
return new Pluche_Beer(TXTNaam_pluche.Text, open_foto.FileName, "(Wasprogramma: " + TXT_wasprogramma.ToString() + " Graden Celsius");
}
return new Elektronische_Beer(TXTNaam_elekro.Text, open_foto.FileName, "aantal Batterijen: " + CMBOBatterijen.ToString());
}
Hopefully Pluche_Beer and Elektronisch_Beer inherent from Berenlijst. Otherwise you'll have to revise your logic in a broader way.

Categories