I've just started learning C# using Visual Studio 2015, and my task is to create a lottery program that saves the generated numbers into a database. I've tried various methods and none of them seem to make any additions to my table. Can anyone help me understand what I need to do take an Integer that has been generated and converted into a string/ textbox and then insert that value into my table.
Heres my current code below, button 2 being the button I am trying to use to save the data from the textboxes with.
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.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
//Database details
string connectionString;
SqlConnection connection;
public Form1()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.LottoConnectionString"].ConnectionString;
}
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int[] slot = new int[6];
int counter = 0;
for (int i = 0; i < slot.Length; i++)
{
slot[i] = rnd.Next(0, 100);
}
//Converting generated ints to Strings for display
textBox1.Text = (slot[0].ToString());
textBox2.Text = (slot[1].ToString());
textBox3.Text = (slot[2].ToString());
textBox4.Text = (slot[3].ToString());
textBox5.Text = (slot[4].ToString());
textBox6.Text = (slot[5].ToString());
//Incrementing Counter checks matches
if (numericUpDown1.Value == slot[0])
{
counter += 1;
}
if (numericUpDown2.Value == slot[1])
{
counter += 1;
}
if (numericUpDown3.Value == slot[2])
{
counter += 1;
}
if (numericUpDown4.Value == slot[3])
{
counter += 1;
}
if (numericUpDown5.Value == slot[4])
{
counter += 1;
}
if (numericUpDown6.Value == slot[5])
{
counter += 1;
}
//display total matches
textBox7.Text = ("You got" + counter + "/6 matches!");
LottoDataSetTableAdapters.ResultsTableAdapter resultsTableAdapter =
new LottoDataSetTableAdapters.ResultsTableAdapter();
resultsTableAdapter.Insert((slot[0].ToString()), (slot[1].ToString()), (slot[2].ToString()), (slot[3].ToString()), (slot[4].ToString()), (slot[5].ToString()));
}
private void button2_Click(object sender, EventArgs e)
{
// Adding Data to Database
string query = "INSERT INTO Results VALUES (#First)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Second", textBox2.Text);
command.Parameters.AddWithValue("#Third", textBox3.Text);
command.Parameters.AddWithValue("#Fourth", textBox4.Text);
command.Parameters.AddWithValue("#Fifth", textBox5.Text);
command.Parameters.AddWithValue("#Sixth", textBox6.Text);
}
}
}
}
All help will be greatly appreciated.
Your INSERT statement is missing the other parameters in the VALUES portion. You also need to execute the command and you were missing brackets for the using of the connection.
private void button2_Click(object sender, EventArgs e)
{
// Adding Data to Database
string query = "INSERT INTO Results (First, Second, Third, Fourth, Fifth, Sixth) VALUES (#First, #Second, #Third, #Fourth, #Fifth, #Sixth)";
using (var connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Second", textBox2.Text);
command.Parameters.AddWithValue("#Third", textBox3.Text);
command.Parameters.AddWithValue("#Fourth", textBox4.Text);
command.Parameters.AddWithValue("#Fifth", textBox5.Text);
command.Parameters.AddWithValue("#Sixth", textBox6.Text);
command.ExecuteNonQuery();
}
}
}
It looks like this question as been asked and answered before - have a look here - How to insert data into SQL Server
edit - my first impression was wrong, I can't see where you are executing your query against the db. its been a while since it have written ado code manual without using an orm so forgive me if i am wrong.
Related
i am encountering an error when trying to set up an insert command into my database, it appears to be with the connection string. I am extremely new to all this and am trying to get the correct code in order to upload into my database and assume that the syntax i am using may be wrong and the cause of the error.
Here is the code a little bit clearer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace ComputingProjectwh.TestPages._1._Further_Mechanics
{
public partial class Moments_and_Energy_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
if (!this.IsValid)
return;
int score = 0;
List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 };
foreach (var element in list)
{
if (element.SelectedValue == "Correct")
{
score++;
}
}
Response.Write("you scored: " + score);
Button1.Visible = false;
if (score != 0);
{
SqlConnection sqlConnection1 = new SqlConnection (#"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
I am really not sure what the problem is and cant seem to find an answer on the internet. Any help would be greatly appreciated.
When connecting to MSSQL, there is no initialcatalog, You are using a wrong connection string.
This is the correct syntax:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or in your case, for trusted connection:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
With your data:
SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;");
InitialCatalog is two separate words initial catalog.
Hello can someone please help me? when i am trying to get a string value from a table on my sql server database table it says that i can not convert string to int, but i dont want to convert the value to int. as the values in the table are "Admin" and "General User".
by the way i am using sql server 2014
the variable that i use to capture the string is cap and i declared it as a string.
and when i write the code.
conn.Open();
string query_inicio = "select * from usuarios where USU_Usuario = '" + txtusuario.Text + "' AND USU_Contra ='" + txtcontra.Text + "'";
SqlCommand exe_query_inicio = new SqlCommand(query_inicio, conn);
SqlDataReader leer_exe;
try
{
leer_exe = exe_query_inicio.ExecuteReader();
if (leer_exe.Read())
{
cap = leer_exe.GetString("Admin");
MessageBox.Show("CONECTADO");
if (cap.Equals("Admin"))
{
Reporte_Detallado IB = new Reporte_Detallado();
IB.Show(this);
this.Hide();
}
}
else if (leer_exe.Read() == false)
{
MessageBox.Show("Inicio Fallido, Verifique Conexion");
}
it underlines the cap = leer_exe.GetString("Admin"); and says that i can't convert string to int.
i have the same code using a mysql datbase and it works. now i am trying to do it with microsoft sql server. so the only thing i changed from the mysql version was instead of mysqlconection and those database code lines to sqlconnection and the other variations.
here is my complete code. i hope someone can help me.
by the way i am coding in c#.
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 ClimateReports
{
public partial class Login : Form
{
SqlConnection conn = ConexionBD.ObtenerConexion();
string cap;
public Login()
{
InitializeComponent();
}
private void btncancelar_Click(object sender, EventArgs e)
{
this.Dispose();
}
private void btniniciar_Click(object sender, EventArgs e)
{
conn.Open();
string query_inicio = "select * from usuarios where USU_Usuario = '" + txtusuario.Text + "' AND USU_Contra ='" + txtcontra.Text + "'";
SqlCommand exe_query_inicio = new SqlCommand(query_inicio, conn);
SqlDataReader leer_exe;
try
{
leer_exe = exe_query_inicio.ExecuteReader();
if (leer_exe.Read())
{
cap = leer_exe.GetSqlString("Admin");
MessageBox.Show("CONECTADO");
if (cap.Equals("Admin"))
{
Reporte_Detallado IB = new Reporte_Detallado();
IB.Show(this);
this.Hide();
}
}
else if (leer_exe.Read() == false)
{
MessageBox.Show("Inicio Fallido, Verifique Conexion");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
}
}
The problem is this line:
cap = leer_exe.GetString("Admin");
GetString takes an int32 as its argument.
If you want to access a column by its name, you should use Item instead:
cap = leer_exe["Admin"] as string;
Or, if you know what column "Admin" is, you can replace it with its position index. If it's the 4th column in the resultset, you'd use index 3 (because it's base 0):
cap = leer_exe.GetString(3);
Another ASP.NET C# noobie question...
The following codebehind populates a dropdown list from a database. There are three columns in the table (ID, ItemType & BinType). I need to be able to return the correct BinType for the row selected by the user:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
// Global variable for SqlConnection
OleDbConnection con = new OleDbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// specifying sqlconnection string
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
// Select rows from database where the ItemType field isn't empty. Sort them alphabetically by ItemType
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM NF_WhatWasteWhere WHERE ItemType <>'' Order By ItemType"))
{
//Open the connection and populate the dropdown list with ID and Itemtype
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ItemType1.DataSource = cmd.ExecuteReader();
ItemType1.DataTextField = "ItemType";
ItemType1.DataValueField = "ID";
ItemType1.DataBind();
con.Close();
}
}
// Add a non selectable "Select Item" row at the top of the dropdown list
ItemType1.Items.Insert(0, new ListItem("--Select Item--", "0"));
}
}
protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
{
//
// *** Stuff needs to go here in order to continue with the following conditional statement ***
//
if (ItemType1.SelectedValue == "Green")
{
BinResultTest.Text = "<div class='greenBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>green bin</strong>.</p></div>";
}
else if (ItemType1.SelectedValue == "Black")
{
BinResultTest.Text = "<div class='blackBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>black bin</strong>.</p></div>";
}
else
{
BinResultTest.Text = "<div class='noBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should <strong>NOT</strong> be disposed of in a green or black bin.</p></div>";
}
}
}
What do I need to do to get the conditional statement to work? I presume I need to run another database query - something like the following:
SELECT BinType FROM NF_WhatWasteWhere WHERE ID=" + ItemType1.DataValueField
However, I'm not sure how to code this to establish the connection and return the result.
Any help appreciated.
Thanks.
Edit***
Okay then in protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
You can do something similar to what you did with your first query but use an OdbcDataReader
string binValue;
int idHolder = ItemType1.SelectedValue;
con.ConnectionString =System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
using (OleDbCommand cmd = new OleDbCommand("SELECT BinType FROM NF_WhatWasteWhere WHERE ID = #Id;"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Id",idHolder);
cmd.Connection = con;
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
if(!DBNull.Value.Equals(reader["BinType"]))
{
binValue = Convert.ToString(reader["BinType"]);
}
}
con.Close();
//Then all your conditionals based off of binValue....
Something like this but maybe a bit more well writen.
As part of a project I'm putting together, I have an Arduino updating a MySQL database via C♯ and, in another location I have another C♯ program doing a simple SELECT query on the database, and communicating its findings to another Arduino via Serial. I have written most of the code for this second program but am having some annoying issues at the end of it all.
Below is the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Xml;
using System.IO.Ports;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string hkday;
string hkall;
//SERIAL
SerialPort serialPort1 = new SerialPort();
serialPort1.PortName = "COM4";
serialPort1.BaudRate = 9600;
serialPort1.NewLine = "\n";
//OPEN SERIAL
serialPort1.Open();
//SQL
string connString = "Server=xxxx;Uid=xxxx;Password=xxxx;Port=xxxx;Database=xxxx;";
MySqlConnection conn = new MySqlConnection(connString);
MySqlCommand command1 = conn.CreateCommand();
command1.CommandText = "Select USERS from HK where UPTIME='HKDAY'";
MySqlCommand command2 = conn.CreateCommand();
command2.CommandText = "Select USERS from HK where UPTIME='HKALL'";
//EXECUTE QUERIES
if (_continue = true)
{
conn.Open(); //Connect
MySqlDataReader reader1 = command1.ExecuteReader();
while (reader1.Read())
{
//Write to value and string
Console.WriteLine(reader1["USERS"].ToString());
hkday = reader1["USERS"].ToString();
}
Console.ReadLine();
_continue = false;
conn.Close(); //Disconnect
}
else
{
conn.Open(); //Connect
MySqlDataReader reader2 = command1.ExecuteReader();
while (reader2.Read())
{
//Write to console and string
Console.WriteLine(reader2["USERS"].ToString());
}
hkall = reader2["USERS"].ToString();
Console.ReadLine();
_continue = true;
conn.Close(); //Disconnect
//WRITE STRINGS TO SERIAL
serialPort1.WriteLine(
String.Format(hkday, hkall));
}
serialPort1.Close();
}
public static bool _continue { get; set; }
}
}
I can't work out how my section titled WRITE STRINGS TO SERIAL needs to be syntaxed and placed within the code to be able to reference both 'hkday' and 'hkall'
My 'if (_continue = true)' flag doesn't seem to work, and I'm not sure why.
I think that if these two issues are solved, the program ought to work, can you see any other glaring issues?
Thank you, I know these are only tiny issues, but I can't seem to work them out.
Potentially important: I'm trying to get the output as '123,456\n' as my arduino program already recognises this as its input.
UPDATE
Having received the answers I have, I have compounded this project with the other one I'm currently doing to try and have an arduino update a MySQL database via C# and then also have it download the table's data that it isn't updating to display out through another arduino.
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.IO.Ports;
using MySql.Data.MySqlClient;
namespace SQL_Scraper
{
public partial class Sandro : Form
{
//Serial Settings
SerialPort UNO = new SerialPort("COM4", 9600);
SerialPort MEGA = new SerialPort("COM3", 9600);
//Incoming Data String
string RxString;
//Int for download
int? vnday = 0;
int? vnall = 0;
public Sandro()
{
InitializeComponent();
//Open UNO port
UNO.Open();
//Open MEGA Port
MEGA.Open();
}
private void MEGA_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
}
private void Sandro_FormClosing(object sender, FormClosingEventArgs e)
{
if (UNO.IsOpen | MEGA.IsOpen)
{
UNO.Close();
MEGA.Close();
}
}
private void DisplayText(object sender, EventArgs e)
{
}
private void Begin_Click(object sender, EventArgs e)
{
//Turn off start button
Begin.Enabled = false;
//?
this.Invoke(new EventHandler(DisplayText));
//Create Event Handler if data is receiverd
MEGA.DataReceived += new SerialDataReceivedEventHandler(MEGA_DataReceived);
string SQLString = "Server=benchmarkcount.db.9506323.hostedresource.com;Uid=benchmarkcount;Password=Watercress2428;Port=3306;Database=benchmarkcount;";
MySqlConnection SQLConnection = new MySqlConnection(SQLString);
//Receive data
RxString = MEGA.ReadExisting();
//Append Serial Input to Output box)
outputBox.AppendText(RxString);
//Get Unsaved input from text box
string input = outputBox.Text;
string[] inputLines = input.Split('\n');
//Upload findings from MEGA to SQL
foreach (string line in inputLines)
{
if (line.EndsWith("\r")) //Makes sure line is complete
{
if (line.StartsWith("Today's total users: "))
{
string dayUsers = line.Substring(20).Trim();
MySqlCommand UpdateHKDAY = SQLConnection.CreateCommand();
UpdateHKDAY.Parameters.AddWithValue("param1", dayUsers);
UpdateHKDAY.CommandText = "UPDATE HK SET USERS=?param1 WHERE UPTIME='HKDAY'";
SQLConnection.Open();
UpdateHKDAY.ExecuteNonQuery();
SQLConnection.Close();
}
else if (line.StartsWith("All-time total users: "))
{
string allUsers = line.Substring(21).Trim();
MySqlCommand UpdateHKALL = SQLConnection.CreateCommand();
UpdateHKALL.Parameters.AddWithValue("param2", allUsers);
UpdateHKALL.CommandText = "UPDATE HK SET USERS=?param2 WHERE UPTIME='HKALL'";
SQLConnection.Open();
UpdateHKALL.ExecuteNonQuery();
SQLConnection.Close();
}
}
}
//Only keep unparsed text in text box
outputBox.Text = inputLines[inputLines.Length - 1];
//Download Numbers Query
MySqlCommand DownUsers = new MySqlCommand("Select USERS, UPTIME from VN where UPTIME IN ('VNDAY', 'VNALL')", SQLConnection);
//Open Connection
SQLConnection.Open();
//Execute Downloading Numbers
MySqlDataReader theResults = DownUsers.ExecuteReader();
while (theResults.Read())
{
switch (theResults["UPTIME"] as string)
{
case "VNDAY":
vnday = theResults["USERS"] as int?;
break;
case "VNALL":
vnall = theResults["USERS"] as int?;
break;
}
}
//Do things with the results
UNO.WriteLine(String.Format("{0},{1}", vnday, vnall));
Console.WriteLine(String.Format("{0},{1}", vnday, vnall));
//Close Connection
SQLConnection.Close();
}
private void Sandro_Load(object sender, EventArgs e)
{
}
private void Cease_Click(object sender, EventArgs e)
{
Begin.Enabled = true;
Cease.Enabled = false;
}
}
}
However, I would like to be able to check this data - the data being sent to the arduino - in my inputBox to make sure it's in the format "vnday, vnall\n"
Your question and example has too many contradictions. It appears that you are under impression that there is static persistence between separate app runs. There isn't. All your static variables will be cleared with each run. It would be different if you had a method that you called in a loop inside the same app domain.
Also, judging by your variable names and your output requirement, the USERS field is a numeric.
So, assuming you have following table:
USERS UPTIME
------ ------
123456 HKALL
234567 HKDAY
following code:
public static void Main()
{
int? hkday = 0;
int? hkall = 0;
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS, UPTIME from HK where UPTIME IN ('HKDAY', 'HKALL')", conn);
MySqlDataReader reader = cmd.ExecuteReader();
//this assumes that there is only one record per 'HKDAY' and 'HKALL',
//otherwise the last value will be stored
while (reader.Read())
{
switch (reader["UPTIME"] as string)
{
case "HKDAY":
hkday = reader["USERS"] as int?;
break;
case "HKALL":
hkall = reader["USERS"] as int?;
break;
}
}
}
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
will output:
234,567
123,456
Or if you desire to run independent queries:
private static int? GetUSERS(string hkval)
{
using (MySqlConnection conn = new MySqlConnection("..."))
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("Select USERS from HK where UPTIME=#hkval", conn);
cmd.Parameters.AddWithValue("hkval", hkval);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
return reader["USERS"] as int?;
return null;
}
}
public static void Main()
{
int hkday = (int)GetUSERS("HKDAY");
int hkall = (int)GetUSERS("HKALL");
Console.WriteLine(String.Format("{0:N0}\n{1:N0}\n", hkday, hkall));
}
You could also pass HKDAY/HKALL as a parameter to you app using args.
I'm not a C programmer but know a lot of serial ports, I suppouse that this solves your first issue.
//WRITE STRINGS TO SERIAL
serialPort1.Write(hkday); // do not append line feed
serialPort1.WriteLine(hkall); // append line feed
I'm doing like a Mcdonalds' control panel to choose
what clients want to take. I'm doing it with Windows Forms
using C#. What I made was creating a class called products
and after in Form1.cs I made a List where I'll put the
products read from database.
I managed to do this and show the results on a DataGrid.
My problem is that when I make the selection of the products
and then I click on the button Send, the Datagrid doesn't refresh automatically. I have to close the program and when
i restart it i can see the changes.
My question is, does anyone know how to update de Datagrid
whitout restarting the program?
Thanks very much, I add my code below:
![]My_windows_form1
#
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 MySql.Data.MySqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
MySqlConnection conn = new MySqlConnection();
String connectionString = "Server=127.0.0.1; Database=mydatabase; Uid=root; Pwd=;";
List<products> listproducts = new List<products>();
public string product;
public string quantity;
public Form1()
{
InitializeComponent();
startConn();
}
private void startConn()
{
try
{
conn.ConnectionString = connectionString;
conn.Open();
textBox3.Text= "Correct connection";
//we call the function READ
read();
}
catch (MySqlException)
{
textBox3.Text="An error has ocurred";
}
}
public void read()
{
MySqlCommand instruccio = conn.CreateCommand();
instruccio.CommandText = "Select * from products";
MySqlDataReader search = instruccio.ExecuteReader();
while (search.Read())
{
products prod = new products();
prod.IdProd = search["idProd"].ToString();
prod.Name = search["nomProd"].ToString();
prod.Quantity = Int32.Parse(search["quantitat"].ToString());
listproducts.Add(prod);
}
dataGridView1.DataSource = listproducts;
search.Close();
search.Dispose();
}
private void btnEnviar_Click(object sender, EventArgs e) //Button Send (Enviar in spanish)
{
try
{
//before updating the stock in database we query the total quantity of the product selected
MySqlCommand instruccio1 = connexio.CreateCommand();
instruccio1.CommandText = "Select quantitat from productes where `nomProd`='"+ this.product +"'";
MySqlDataReader read = instruccio1.ExecuteReader();
int result = 0;
while (read.Read())
{
resultat=Int32.Parse(read["quantitat"].ToString());
}
read.Dispose();
instruccio1.Dispose();
if (this.quantity != 0)
{
if (result > this.quantity)
{
int difference = result - this.quantity;
MySqlCommand instruccio2 = conn.CreateCommand();
instruccio2.CommandText = "UPDATE products set `quantitat`='" + this.difference + "' where products.nomProd='" + this.product + "'";
instruccio2.ExecuteNonQuery();
conn.Close();
startConn();
textBox1.Text= "";
textBox2.Text = "";
this.quantity = "";
this.product = "";
}
else
{
MessageBox.Show("There's no quantity.");
}
}
catch (Exception xe)
{
MessageBox.Show("",xe.Message);
}
}
private void btnEsborrar_Click(object sender, EventArgs e) //Erase button
{
this.quantity = "";
this.product = "";
this.aEnviar = 0;
textBox1.Text = quantity;
textBox2.Text = product;
}
....
....
what you can do is the following:
Add a timer control on your form and set the time you want its Tick event to be fired, it is put in the Interval property in milliseconds.
on this event call your function startConn.
and thats it, very easy :)
In your read() method before
dataGridView1.DataSource = listproducts;
add
dataGridView1.DataSource = null;
Then call your startConn() method whenever you want.