when maxlevel equal 0 prevent user from add this item - c#

I set maxlvl to 5000, so it is decreasing when you take out product
maxlvl mean for every product you have the limit (maxlvl=5000) in like month
I want to set condition when maxlvl = 0 prevent user from taking this product
I'm new and I don't know how to link condition with db and which condition should i use
note: I'm learning and i don't care about SQL injection right now and I want to keep the code simple
using System;
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;
using System.Data.SqlClient;
namespace WindowsFormsApplication7
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'invoiceDataSet12.product' table. You can move, or remove it, as needed.
this.productTableAdapter.Fill(this.invoiceDataSet12.product);
using (invoiceEntities2 cc1 = new invoiceEntities2())
{
productBindingSource.DataSource = cc1.product.ToList();
}
}
private void save_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=NAWAF;Initial Catalog=invoice;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [invoice].[dbo].[Qout]
([id]
,[empnumber]
,[pname]
,[cproduct]
,[qnt])
VALUES
('" + tid.Text + "' ,'" + temp.Text + "' , '" + pcom.Text + "' , '" + pcomc.Text + "' , '" + qotext.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select id,empnumber,pname,cproduct,qnt from Qout where id like '" + tid.Text + "'", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
SqlCommand ccm = new SqlCommand("UPDATE product SET quantity -= '" + qotext.Text + "' FROM product WHERE Product_name like '" + pcom.Text + "'", con);
ccm.ExecuteNonQuery();
SqlCommand bbc = new SqlCommand("UPDATE product SET Maxlvl -= '" + qotext.Text + "' FROM product WHERE Product_name like '" + pcom.Text + "'", con);
bbc.ExecuteNonQuery();
temp.Text = "";
pcom.Text = "";
pcomc.Text = "";
qotext.Text = "";
con.Close();
}

Related

the connectionstring property has not been initialized; Data type mismatch in criteria expression; database not updating

I'm new to c# and the "the connectionstring property has not been initialized" is my problem. I've searched and tried everything I saw on the internet, but it doesn't help me at all. I don't know what to do anymore, Please help :(
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.Data.OleDb;
namespace salon
{
public partial class Form4 : Form
{
OleDbConnection conn = new OleDbConnection();
public Form4()
{
InitializeComponent();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/myDB.accdb";
}
private void Form4_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'myDBDataSet.tblCustomerInfo' table. You can move, or remove it, as needed.
this.tblCustomerInfoTableAdapter.Fill(this.myDBDataSet.tblCustomerInfo);
}
private void btnContinue_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"insert into tblCustomerInfo(CustomerName, PhoneNo, Email) values ('" + txtName.Text + "','" + txtNo.Text + "','" + txtEmail.Text + "'";
cmd.Connection = conn;
cmd.ExecuteNonQuery();
conn.Close();
string date = System.DateTime.Today.ToString("ddmmyy");
MessageBox.Show("Your Information: " + Environment.NewLine + "Name: " + txtName.Text + Environment.NewLine + "Phone no.: " + txtNo.Text + Environment.NewLine + "Email: " + txtEmail.Text + Environment.NewLine + Environment.NewLine + "Your chosen date is: " + timePicker.Value);
MessageBox.Show("Your date is successfully reserved");
Form1 frm1 = new Form1();
frm1.Show();
this.Hide();
}
}
}
Please help me with this one, I am new to c# and I don't know how to fix this. I tried searching and all but no luck. #un-lucky suggested parameterized queries but i don't know how to. I tried searching for it and no luck.
data type mismatch
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.Data.OleDb;
namespace salon
{
public partial class Form4 : Form
{
OleDbConnection conn = new OleDbConnection();
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'myDBDataSet.tblCustomerInfo' table. You can move, or remove it, as needed.
this.tblCustomerInfoTableAdapter.Fill(this.myDBDataSet.tblCustomerInfo);
}
private void btnContinue_Click(object sender, EventArgs e)
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/myDB.accdb";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = conString;
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"insert into tblCustomerInfo(CustomerName, PhoneNo, Email) values ('" + txtName.Text + "','" + txtNo.Text + "','" + txtEmail.Text + "')";
cmd.Parameters.AddWithValue("#CustomerName", txtName.Text);
cmd.Parameters.AddWithValue("#PhoneNo", txtNo.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.ExecuteNonQuery();
conn.Close();
MessageBox.Show("Your Information: " + Environment.NewLine + "Name: " + txtName.Text + Environment.NewLine + "Phone no.: " + txtNo.Text + Environment.NewLine + "Email: " + txtEmail.Text + Environment.NewLine + Environment.NewLine + "Your chosen date is: " + timePicker.Value);
MessageBox.Show("Your date is successfully reserved");
Form1 frm1 = new Form1();
frm1.Show();
this.Hide();
}
}
}
UPDATE
I fixed the error about the data type mismatch but now when i start to debug it the database is not updating what's wrong? please help
You have to initialize the ConnectionString property of the OleDbCommand, for that you can use the constructor or else you can initialize them later by setting the corresponding value to the property. Let conString be a global string variable which is used to store the connection string and are initialized like the following:
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Application.StartupPath + "/myDB.accdb"
Now you can define the connection like this
OleDbConnection conn = new OleDbConnection(conString );
or like this:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = conString;
Few other things that you have to notice is that:
You have syntax errors in your insert query, that means you missed the closing bracket at the end of the query.
Actually, using plain text queries will not be a good option, I strongly recommend you to use parameterization instead.

CheckBox Not Sending Checked Value to Access Database C# Asp

This is my C# code and my issue as the title says is my checkbox values are not going into my access database, or at least not changing them.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
Label1.Text = (string)Session["sesionicontrol"];
}
protected void txtPass_TextChanged(object sender, EventArgs e)
{
}
protected void check1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
//Declare Variables
string username = txtEmailLogin.Text;
string password = txtPasswordLogin.Text;
username = username.Trim().ToLower();
password = password.Trim().ToLower();
//Handle null or empty fields
if ((string.IsNullOrEmpty(username)) || (string.IsNullOrEmpty(password)))
{
lblError.Text = "Please Enter a vaild Username or Password";
}
else if (((username.Contains("#mu.edu") || (username.Contains("#marquette.edu")))))
{
//Run select query and populate a table, then check to see if the user and pass are in that table
OleDbConnection conn = null;
DataTable dt = new DataTable();
try
{
string connString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "Select Count(*) From Team Member Where Email = ? AND Pass = ?";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
}
catch (Exception ex)
{
// handle error here
}
finally
{
conn.Close();
}
//checking if there is a result in the virtual table, if there is they successfully logged in
if (dt.Rows.Count >= 0)
{
lblError.Text = "Welcome!";
/// Take to Homepage
CommonClass.txtEmail = txtEmailLogin.Text;
Server.Transfer("HomePage.aspx", true);
}
else
{
lblError.Text = "Incorrect Username or Password";
}
}
}
protected void btnRegister_Click(object sender, EventArgs e)
{
OleDbConnection conn = null;
DataTable gridTable = new DataTable();
try
{
string connString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new OleDbConnection(connString);
string query = "INSERT INTO [Team Member] (FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major) VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" + txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "')";
string query1 = "INSERT INTO [Team Member] (Soccer, Basketball, Football, Softball) VALUES('" + c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
conn.Open();
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
lblError1.Text = ("Registered Successfully");
}
catch (Exception ex)
{
lblError1.Text = ("Error occurred: " + ex.Message);
}
finally
{
conn.Close();
}
}
protected void btnReg_Click(object sender, EventArgs e)
{
txtFirst.Visible = !txtFirst.Visible;
txtLast.Visible = !txtLast.Visible;
txtEmail.Visible = !txtEmail.Visible;
txtPass.Visible = !txtPass.Visible;
txtPassConfirm.Visible = !txtPassConfirm.Visible;
btnRegister.Visible = !btnRegister.Visible;
btnReg.Visible = !btnReg.Visible;
c1.Visible = !c1.Visible;
c2.Visible = !c2.Visible;
c3.Visible = !c3.Visible;
c4.Visible = !c4.Visible;
txtAge.Visible = !txtAge.Visible;
txtHobbies.Visible = !txtHobbies.Visible;
txtFavorite.Visible = !txtFavorite.Visible;
txtMajor.Visible = !txtMajor.Visible;
lbl1.Text = "Sports you want to play";
lbl2.Text = "Age";
lbl3.Text = "Hobbies";
lbl4.Text = "Favorite Color";
lbl5.Text = "Major";
}
protected void c2_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void c1_CheckedChanged(object sender, EventArgs e)
{
}
}
My database looks like this
If you are appending to Access Yes/No fields then I would try removing the single quotes (') from the second INSERT INTO line:
string query1 = "INSERT INTO [Team Member]
(Soccer, Basketball, Football, Softball)
VALUES(" + c1.Checked.ToString() + ", "
+ c2.Checked.ToString() + ", "
+ c3.Checked.ToString() + ", "
+ c4.Checked.ToString() + ")";
First, The reason your check box values never get inserted is because your OleDbCommand is defined like this:
OleDbCommand cmd = new OleDbCommand(query, conn);
Using query as the command.text. query1 is never referenced to this and thus never executes.
Second (more important), you need to have the insert statement as one statement, not 2. Calling 2 Insert statements would cause 2 rows to added to the table. One containing values from query, and one containing the checkbox value from query1. You should define your query in one string like this
string query = "INSERT INTO [Team Member] " +
"(FirstName, LastName, Email, Pass, Age, Hobbies, FavoriteColor, Major, Soccer, Basketball, Football, Softball) " +
"VALUES('" + txtFirst.Text + "','" + txtLast.Text + "', '" + txtEmail.Text + "','" + txtPass.Text + "','" +
txtAge.Text + "','" + txtHobbies.Text + "', '" + txtFavorite.Text + "','" + txtMajor.Text + "','" +
c1.Checked.ToString() + "', '" + c2.Checked.ToString() + "', '" + c3.Checked.ToString() + "', '" + c4.Checked.ToString() + "')";

trying to create a refreshing button for gridview

I have made an c# program to access a database and write some data to it, and show it in a grid-view.
That all works but now i want the grid-view to refresh because it wont show the data i just entered into the database
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data;
namespace ForexDev
{
public partial class Form1 : Form
{
private OleDbConnection Database1;
private OleDbCommand oledbcmd = new OleDbCommand();
private string connParam = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\floortje\Documents\Visual Studio 2010\Projects\ForexDev\ForexDev\Database11.accdb;Persist Security Info=False";
public Form1()
{
Database1 = new OleDbConnection(connParam);
InitializeComponent();
}
private void btnsave_Click(object sender, EventArgs e)
{
try
{
Database1.Open();
oledbcmd.Connection = Database1;
oledbcmd.CommandText = "INSERT INTO Forex ([Order],[Tijd gekocht],Type,Groote,Symbool,[Koers inkoop],[S/l],[T/p],[Koers Verkoop],[Profit/Loss]) VALUES ('" + this.txtOrder.Text + "','" + this.txtTijd.Text + "','" + this.txtType.Text + "','" + this.txtgroote.Text + "','" + this.txtSymb.Text + "','" + this.txtKoop.Text + "','" + this.StopLoss.Text + "','" + this.TakeProfit.Text + "','" + this.txtVerkoop.Text + "','" + this.Winstverl.Text + "');";
oledbcmd.CommandType = CommandType.Text;
int temp = oledbcmd.ExecuteNonQuery();
dataGridView1.Refresh();
dataGridView1.Update();
Database1.Close();
if (temp > 0)
{
MessageBox.Show("Added");
}
else
{
MessageBox.Show("Failed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database11DataSet.Forex' table. You can move, or remove it, as needed.
this.forexTableAdapter.Fill(this.database11DataSet.Forex);
}
private void button2_Click(object sender, EventArgs e)
{
Database1.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Database1.Open();
this.dataGridView1.Refresh();
this.dataGridView1.Update();
Database1.Close();
}
}
}
I want to thank you tariq for putting me on the right track, i did not mark your answer as the answer to my problem because of the following :
The answer to my problem was that i needed to bind the database to the gridview like this :
(and correct me if this is not databinding)
{
Database1.Open();
oledbcmd.Connection = Database1;
oledbcmd.CommandText = textBox1.Text;
oledbcmd.CommandText = "DELETE FROM Forex ([Order],[Tijd gekocht],Type,Groote,Symbool,[Koers inkoop],[S/l],[T/p],[Koers Verkoop],[Profit/Loss]) VALUES ('" + this.txtOrder.Text + "','" + this.txtTijd.Text + "','" + this.txtType.Text + "','" + this.txtgroote.Text + "','" + this.txtSymb.Text + "','" + this.txtKoop.Text + "','" + this.StopLoss.Text + "','" + this.TakeProfit.Text + "','" + this.txtVerkoop.Text + "','" + this.Winstverl.Text + "');";
oledbcmd.CommandType = CommandType.Text;
int temp = oledbcmd.ExecuteNonQuery();
dataGridView1.DataSource = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\floortje\Documents\Visual Studio 2010\Projects\ForexDev\ForexDev\Database11.accdb;Persist Security Info=False";
dataGridView1.Refresh();
this.dataGridView1.Refresh();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
ds.Tables.Add(dt);
OleDbDataAdapter dd = new OleDbDataAdapter();
dd = new OleDbDataAdapter("Select * From Forex", Database1);
dd.Fill(dt);
dataGridView1.DataSource = dt.DefaultView;
Database1.Close();
Add this after making updates
dataGridView1.DataBind();

myReader looking for .mdb and not .accdb

im currently in my first year on university and c# is relatively new to me.
im currently working on accessing a database through a form for a made up company for one of my assignments and I cant get through an error that returns saying that myReader is trying to find the database called Jap1.mdb even though the database I have it linked to and successfully connecting to called Jap1.accdb.
the connection to the database works fine as I have a datagrid that produces all the information in the database and allows me to search through it so I am unsure as to why it is trying to find Jap1.mdb
this is the code I currently have in my form:
using System;
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;
using System.Data.OleDb;
namespace customer_play
{
public partial class customersfrm : Form
{
OleDbConnection myConn;
OleDbDataAdapter myDataAdapter;
OleDbCommandBuilder cb;
DataSet ds;
string myConnection;
public customersfrm()
{
InitializeComponent();
}
private void customersfrm_Load(object sender, EventArgs e)
{
myConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + AppDomain.CurrentDomain.BaseDirectory + "jap1.accdb";
myConn = new OleDbConnection(myConnection);
myDataAdapter = new OleDbDataAdapter();
myDataAdapter.SelectCommand = new OleDbCommand(" select * Jap1.CustomerDetails ;", myConn);
cb = new OleDbCommandBuilder(myDataAdapter);
myConn.Open();
ds = new DataSet();
myConn.Close();
}
private void addcustbtn_Click(object sender, EventArgs e)
{
string Query = "insert into Jap1.CustomerDetails (myFirstName,mySecondName,myAddress,myCity,myPostCode,myNumber,myEmailAddress,myDateOfBirth,my18Plus) values('" + this.firstnametxt.Text + "','" + this.secondnametxt.Text + "', '" + this.addresstxt.Text + "', '" + this.citytxt.Text + "', '" + this.postcodetxt.Text + "', '" + this.numbertxt.Text + "', '" + this.emailtxt.Text + "', '" + this.dobpicker.Text + "', '" + this.eighteenchkbx.Checked + "') ;";
OleDbCommand cmdDataBase = new OleDbCommand(Query, myConn);
OleDbDataReader myReader;
try {
myConn.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("New Customer Has Been Added To The Database");
firstnametxt.Text = "";
secondnametxt.Text = "";
addresstxt.Text = "";
citytxt.Text = "";
postcodetxt.Text = "";
numbertxt.Text = "";
emailtxt.Text = "";
dobpicker.Text = "";
eighteenchkbx.Text = "";
while(myReader.Read()){
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
}
}
}
any help would be hugely appreciated :)

How to achieve a search for a certain year & amount using C#

Here is a small demo of a SQL database, where one can add, update delete members from a SQL server.
There are two tables in a single SQL Server DB, one is “members” second is “overview”.
In members there is distinct ID column and members personal info like name, address telephone etc.
In overview there are only three columns which are dID, year & amount.
There is one single windows form, language is c# and project is built in Visual Studio 2010, and of course data base in SQL Server 2010.
The windows form has a “reset, insert, update & delete” buttons.
There is one more button besides the dID text box where a distinct ID can be inserted and after clicking Search button the last entry made about the member shows by filling all the text boxes where name address telephone appear. This serves the function that member full info can be seen and changes can be made or can be removed from dB.
There are two text boxes in particular, which are Year & Amount, which shows that the member has paid a certain amount for the certain year.
But as I mentioned in the text boxes you can only see the last entry made. What function I want to achieve is that after inserting dID of person x I could only in the year text box able to insert lets say any previous year and the press search which should like normally fill all the text boxes with info, and in the amount text box should show me the entry from the dB that according to the year I entered how much amount is there or there is nothing which means that may be member has not paid for a certain year.
I need help in achieving this logic programmatically therefore I would like to request assistance.
The present program is as follows :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace SQLDatabase
{
public partial class SQLDBDisplay : Form
{
SqlConnection con = new SqlConnection("Data Source=JG-PC\\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=True");
public SQLDBDisplay()
{
InitializeComponent();
}
SqlDataAdapter da;
DataSet ds = new DataSet();
private void btnSearch_Click(object sender, EventArgs e)
{
SqlDataReader reader;
SqlCommand cmd = new SqlCommand();
try
{
string sql = "SELECT * FROM members where dID = '" + txtdID.Text + "' ";
txtYear.Text = sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
sql = "SELECT * FROM Overview where dID = '" + txtdID.Text + "' ";
txtYear.Text = txtYear.Text + " : " + sql;
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
txtYear.Text = reader["Year"].ToString();
txtAmount.Text = reader["Amount"].ToString();
txtdID.Text = reader["dID"].ToString();
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void btnReset_Click(object sender, EventArgs e)
{
txtdID.Text = ""; txtName.Text = ""; txtAddress.Text = "";
txtMobile.Text = ""; txtEmail.Text = ""; txtYear.Text = "";
txtAmount.Text = "";
}
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO members (dID, Name, Address, Email, Mobile) VALUES ( '" + txtdID.Text+ "','" + txtName.Text + "','"
+ txtAddress.Text + "', '" + txtEmail.Text + "', '" + txtMobile.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Overview (dID, Year, Amount) VALUES ('"+ txtdID.Text +"' ,'" + txtYear.Text + "','" + txtAmount.Text +
"')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Scuessfully!!!");
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd = new SqlCommand();
string Sql = "Update members set Name = '" + txtName.Text + "', Address = '" + txtAddress.Text + "', Email = '" +
txtEmail.Text + "', Mobile = '" + txtMobile.Text + "' WHERE dID = '"
+ txtdID.Text + "'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "Update overview set Year = '" + txtYear.Text + "', Amount = '" + txtAmount.Text + "' WHERE dID = '"+ txtdID.Text+"'";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data Scuessfully Updated");
con.Close();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "DELETE FROM members WHERE dID = '"+ txtdID.Text +"'";
con.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = "DELETE FROM overview WHERE dID = '" + txtdID.Text + "'";
cmd.ExecuteNonQuery();
da = new SqlDataAdapter(cmd);
MessageBox.Show("Record Scuessfully Deleted !");
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
}
private void btnClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
} }
To add a solution to the comments people have made regarding parameters and sql injection, i tend to use the code below when connecting to any database.
using(SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING"))
{
try
{
using(SqlCommand command = new SqlCommand())
{
command.CommandText = "SELECT * FROM members where dID = #MyId";
command.Connection = connection;
// Set the SqlDbType to your corresponding type
command.Parameters.Add("#MyId", SqlDbType.VarChar).Value = txtdID.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtID.Text = reader["ID"].ToString();
txtName.Text = reader["Name"].ToString();
txtAddress.Text = reader["Address"].ToString();
txtMobile.Text = reader["Mobile"].ToString();
txtEmail.Text = reader["Email"].ToString();
txtdID.Text = reader["dID"].ToString();
}
}
}
finally
{
connection.Close();
}
}
You need to group your SELECT on the Amount column. A simple answer to your question would be to modify your second select query like this:
sql = "SELECT Year, dID, SUM(Amount) as Amount FROM Overview where dID = '" + txtdID.Text + "' AND Year = " + txtYear.Text + "GROUP BY amount";
Probably, you would like to use the txtYear.Text value for an SQL parameter, so:
txtYear.Text = sql;
and
txtYear.Text = txtYear.Text + " : " + sql;
don't make too much sense in your code.
Of course, this is not the correct way, as it is prone to SQL Injection. I would recommend you to use SQL Stored Procedures, which are definitely safer regarding SQL Injection.
Another improvement to the code quality would be that you should use using statements to enclose the SQLConnection, SQLCommand and SQLDataReader objects initializations.

Categories

Resources