Prevent duplicates in datagrid when databound - c#

after some testing I came with this way to handle my datagrid. dgVariedad_CellEditEnding use the function nombreVariedadDisponible(txtBoxTemporal.Text) to check if the new value already exist in List<Variedad> variedades and it works. The problem is that the value wont be inserted in the database but will be added in the datagrid control, I can't find a way to cancel the new row in the control.
private List<Variedad> variedades = new List<Variedad>();
private void bindVariedad()
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
cmd.CommandText = "SELECT NOMBRE FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
Conexion.abrirConexion();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataTable table = new DataTable("DATAFRUT_VARIEDADES");
da.Fill(table);
table.Columns[0].ColumnName = "Nombre";
dgVariedad.ItemsSource = table.DefaultView;
cmd.CommandText = "SELECT * FROM DATAFRUT_VARIEDADES WHERE ELIMINADO = 'F';";
using (MySqlDataReader dr = cmd.ExecuteReader())
{
variedades.Clear();
while (dr.Read())
{
Variedad var = new Variedad();
var.codigo = Convert.ToInt32(dr[0]);
var.nombre = dr[1].ToString();
var.eliminado = Convert.ToChar(dr[2]);
variedades.Add(var);
}
}
}
}
private void dgVariedad_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
TextBox txtBoxTemporal = e.EditingElement as TextBox;
int indice = e.Row.GetIndex();
if (e.Row.IsNewItem)
{
if (nombreVariedadDisponible(txtBoxTemporal.Text))
{
bool insertExitoso = false;
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
cmd.CommandText = "INSERT INTO DATAFRUT_VARIEDADES VALUES (default, '" + txtBoxTemporal.Text + "', 'F');";
try
{
cmd.ExecuteNonQuery();
insertExitoso = true;
}
catch
{
MessageBox.Show("Error");
}
Conexion.cerrarConexion();
}
if (insertExitoso)
{
variedades.Add(Variedad.cargarUltimoInsert(txtBoxTemporal.Text));
}
}
else
{
e.Cancel = true;
}
}
else
{
using (MySqlCommand cmd = Conexion.con.CreateCommand())
{
Conexion.abrirConexion();
DataRowView dataRow = (DataRowView)dgVariedad.SelectedItem;
cmd.CommandText = "UPDATE DATAFRUT_VARIEDADES SET NOMBRE = '" + txtBoxTemporal.Text + "' WHERE CODIGO = " + variedades[dgVariedad.SelectedIndex].codigo + ";";
try
{
cmd.ExecuteNonQuery();
variedades[dgVariedad.SelectedIndex].nombre = txtBoxTemporal.Text;
}
catch(MySqlException mex)
{
MessageBox.Show("Error " + mex.Message);
}
Conexion.cerrarConexion();
}
}
}
My table on mysql has 3 fields:
int codigo (primary key, auto increment)
string Nombre (Unique) char
char Eliminado -> Eliminado (Deleted) with values (F = false and V =
true)
Here is how I check if the value already exist.
private bool nombreVariedadDisponible(string nombreAComparar)
{
//busca el nombre en la lista "variedades"
foreach (Variedad var in variedades)
{
if (var.nombre.ToLower() == nombreAComparar.ToLower() && var.eliminado == 'F')
return false;
}
return true;
}

Related

How to update SQL Table Using DataGridView Values in C#?

enter image description hereI tried to update selected columns of SQL Database table which from DataGridView. But it said my input string is wrong.So how to fix this.(PO_No is the primary key of PO table and it has identity value and also it is the foreign key of PO_Cart table)
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, decimal UnitPrice, decimal Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice, Total=#Total"
+ "WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = UnitPrice;
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Total;
con.nonquery();
}
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
PO.UpdatePOCartTable(Convert.ToInt32(txtPONo.Text),dataGridView1.Rows[i].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value.ToString()));
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured" + ex.Message);
}
}
When Updating SQL I normally use the following code:
String CommandLine = "UPDATE CA_temp_data SET TimePast=#selectTot WHERE TicketNumber=#id";
using (SqlConnection Conn = new SqlConnection("Data Source=" + hostString + ";User ID=" + usernamestring + ";Password=" + sqlpassword))
{
try
{
SqlCommand cmd = new SqlCommand(CommandLine, Conn);
cmd.Parameters.AddWithValue("#id", ticket);
cmd.Parameters.AddWithValue("#selectTot", time);
using (Conn)
{
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (System.Exception excep)
{
}

code asp.net c# oledb, cookies, if else

Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.

C# DataReader error

I looked for a solution to this problem on the forum, but I didn't find one for my problem. On button click, I receive error:
There is already an open DataReader associated with this Connection which must be closed first.
So, I tried to close all DataReaders after using them, I tried to use CommandBehavior, but none of them worked. I tried to use using(MysqlCommand...) but didn't work. What can I do? The strangest thing is that the code is working, but after each button press, I receive that error again. Any ideas?
Please don't flag question as a duplicate, I know that the question exist here but the answer is missing for my problem I guess.
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 MySql.Data.MySqlClient;
using System.Drawing.Text;
namespace simulator
{
public partial class Simulare : Form
{
public int corect = 0, incorect = 0;
Timer timer;
static string dataA = "SELECT DISTINCT * FROM questions order by rand() limit 1";
public int r1;
public int r2;
public int r3;
public Simulare()
{
InitializeComponent();
this.FormClosing += Form1_FormClosing;
label1.Text = TimeSpan.FromMinutes(30).ToString("mm\\:ss");
label10.Text = corect.ToString();
label12.Text = incorect.ToString();
//FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
}
private void simulare_Load(object sender, EventArgs e)
{
var startTime = DateTime.Now;
timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
{
TimeSpan ts = TimeSpan.FromMinutes(30) - (DateTime.Now - startTime);
label1.Text = ts.ToString("mm\\:ss");
if (ts.Minutes == 00 && ts.Seconds == 00)
{
timer.Stop();
MessageBox.Show("Timpul a expirat. Ai picat!");
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
try
{
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
int totalnu = (int)upad["totalno"];
totalnu++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalnu", totalnu);
int rows = update.ExecuteNonQuery();
}
}
upad.Close();
}
catch (Exception ex2)
{
MessageBox.Show(ex2.Message);
}
}
};
timer.Start();
select();
}
private void select()
{
using (ConnConfig.getConnection())
{
MySqlCommand cmd = new MySqlCommand(dataA, ConnConfig.getConnection());
cmd.CommandType = CommandType.Text;
MySqlDataReader rdra = cmd.ExecuteReader(CommandBehavior.CloseConnection);
try
{
while (rdra.Read())
{
label2.Text = rdra["question"].ToString();
label3.Text = rdra["answer1"].ToString();
label4.Text = rdra["answer2"].ToString();
label5.Text = rdra["answer3"].ToString();
r1 = (int)rdra["option1"];
r2 = (int)rdra["option2"];
r3 = (int)rdra["option3"];
}
rdra.Close();
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
ConnConfig.closeConn();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
int result1 = checkBox1.CheckState == CheckState.Checked ? 1 : 0;
int result2 = checkBox2.CheckState == CheckState.Checked ? 1 : 0;
int result3 = checkBox3.CheckState == CheckState.Checked ? 1 : 0;
using(ConnConfig.getConnection())
{
MySqlCommand cmd = new MySqlCommand(dataA, ConnConfig.getConnection());
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
try
{
while (rdr.Read())
{
if (checkBox1.Checked == false && checkBox2.Checked == false && checkBox3.Checked == false)
{
MessageBox.Show("Bifati minim o casuta!");
return;
}
else
{
if ((result1 == r1) && (result2 == r2) && (result3 == r3))
{
corect++;
label10.Text = corect.ToString();
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
select();
}
else
{
incorect++;
label12.Text = incorect.ToString();
checkBox1.Checked = false;
checkBox2.Checked = false;
checkBox3.Checked = false;
select();
}
if (corect + incorect == 26)
{
int totalalll;
timer.Stop();
button1.Enabled = false;
MySqlCommand upd = new MySqlCommand("select * from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
totalalll = (int)upad["totalall"];
totalalll++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalall=#totalalll where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalalll", totalalll);
Int32 rows = update.ExecuteNonQuery();
}
}
upad.Close();
}
if (corect == 26)
{
MySqlCommand upd = new MySqlCommand("select totalyes from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
int totalda = (Int32)upad["totalyes"];
totalda++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalyes=#totalda where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalda", totalda);
int rows = update.ExecuteNonQuery();
}
}
upad.Close();
MessageBox.Show("Bravos");
}
else
{
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
MySqlDataReader upad = upd.ExecuteReader();
while (upad.Read())
{
int totalnu = (int)upad["totalno"];
totalnu++;
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
{
update.Parameters.AddWithValue("#totalnu", totalnu);
int rows = update.ExecuteNonQuery();
}
}
upad.Close();
MessageBox.Show("Mai invata!");
}
}
}
rdr.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
finally
{
ConnConfig.closeConn();
}
}
}
private void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.WindowsShutDown) return;
if (this.DialogResult == DialogResult.Cancel)
{
e.Cancel = false;
timer.Stop();
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
class ConnConfig
{
private static string conn = "string connection";
public static MySqlConnection connect;
private ConnConfig()
{
}
public static MySqlConnection getConnection()
{
if(connect !=null){
return connect;
}
else
try{
connect = new MySqlConnection(conn);
connect.Open();
return connect;
}
catch(MySqlException e){
throw new Exception("Cannot connect",e);
}
}
public static void closeConn()
{
connect.Close();
}
public static void openConn()
{
connect.Open();
}
}
Change the getConnection function
public static MySqlConnection getConnection()
{
MySqlConnection connect = null;
try
{
connect = new MySqlConnection(connect);
connect.Open();
return connect;
}
catch (MySqlException e)
{
throw new Exception("Cannot connect", e);
}
}
let all the other codes as it is
The root cause of your exception is that you are executing other queries while you are still iterating over the results of an earlier query.
Bottom line you should not nest queries like you do if you use the same connection for the nested queries.
You are using reader to fetch data from SQLCommand upd.
Then you are reading value.
After that you are using another SqlCommand 'update' to update the result..
Even when you use two different SQLCommands, you are using the same connection. Thats the problem. Use a sperate connection for the second SQLCommand and your problem will be solved.
Try this.
after the line
MessageBox.Show("Timpul a expirat. Ai picat!");
add like
MessageBox.Show("Timpul a expirat. Ai picat!");
MySqlConnection conn1 = ConnConfig.getConnection();
MySqlConnection conn2 = new MySqlConnection();
conn2.ConnectionString = conn1.ConnectionString;
conn2.Open();
and then in the line
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection());
change like
MySqlCommand upd = new MySqlCommand("select totalno from accounts where username = '" + Index.textBox1.Text + "'", conn1);
and in line
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", ConnConfig.getConnection()))
change like
using (MySqlCommand update = new MySqlCommand("UPDATE accounts SET totalno=#totalnu where username = '" + Index.textBox1.Text + "'", conn2))

Table not updated in database after changing values from Textbox linked to Selected Item from ListView

This is how it works. I select a row from my listview then I will click "Edit" button which the values from the selected item will also be shown in the registration form. The "Register" button will now then changed to "Update". I am trying to update my customers table after changing inputs from the textboxes on my registration form but there are no changes in my database.
I receive no errors but I might have missed something here.
This is my code here:
private void btnRfrsh_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "SELECT Cust_Lname, Cust_Fname, Cust_MI, Birthdate, Age, Sex, Passport_ID, Address, Contact_Num, Nationality from customers where removed = 0";
MySqlCommand select = new MySqlCommand(query, connect);
MySqlDataReader refresh = select.ExecuteReader();
while (refresh.Read())
{
ListViewItem item;
item = new ListViewItem(refresh.GetString(0));
item.SubItems.Add(refresh.GetString(1));
item.SubItems.Add(refresh.GetString(2));
item.SubItems.Add(refresh.GetString(3));
item.SubItems.Add(refresh.GetString(4));
item.SubItems.Add(refresh.GetString(5));
item.SubItems.Add(refresh.GetString(6));
item.SubItems.Add(refresh.GetString(7));
item.SubItems.Add(refresh.GetString(8));
item.SubItems.Add(refresh.GetString(9));
lviewCust.Items.Add(item);
}
if (refresh.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (lviewCust.SelectedItems.Count > 0)
{
ListViewItem item = lviewCust.SelectedItems[0];
cust_fname.Text = item.SubItems[0].Text;
cust_lname.Text = item.SubItems[1].Text;
cust_mi.Text = item.SubItems[2].Text;
//DateTime bdate = Convert.ToDateTime(item.SubItems[3].Text);
String bdate_string = item.SubItems[3].Text;
DateTime bdate = DateTime.ParseExact(bdate_string, "dd-MM-yyyy", null);
cust_bdate.Value = bdate;
cust_age.Text = item.SubItems[4].Text;
cust_sex.Text = item.SubItems[5].Text;
cust_passid.Text = item.SubItems[6].Text;
cust_nation.Text = item.SubItems[9].Text;
cust_add.Text = item.SubItems[7].Text;
cust_contact.Text = item.SubItems[8].Text;
}
cust_fname.ReadOnly = true;
cust_lname.ReadOnly = true;
cust_mi.ReadOnly = true;
cust_passid.ReadOnly = true;
btnReg.Text = "Update";
btnReg.Name = "btnUpdate";
btnReg.Click -= this.btnReg_Click;
btnReg.Click += this.btnUpdate_Click;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "UPDATE customers SET Age = '" + this.cust_age.Text + "', Nationality = '" + this.cust_nation.Text + "', Address = '" + this.cust_add.Text + "', Contact_Num = '" + this.cust_contact.Text + "' WHERE Cust_Fname = '" + this.cust_fname.Text + "' and Cust_Lname = '" + this.cust_lname.Text + "'";
MySqlCommand update = new MySqlCommand(query, connect);
MySqlDataReader updte = update.ExecuteReader();
MessageBox.Show("Customer Info Updated Successfully");
if (updte.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
cust_fname.Clear();
cust_lname.Clear();
cust_mi.Clear();
cust_bdate.Value = DateTime.Now;
cust_age.Clear();
cust_passid.Clear();
cust_add.Clear();
cust_contact.Clear();
cust_nation.Clear();
cust_fname.ReadOnly = false;
cust_lname.ReadOnly = false;
cust_mi.ReadOnly = false;
cust_passid.ReadOnly = false;
btnReg.Text = "Register";
btnReg.Name = "btnReg";
btnReg.Click -= this.btnUpdate_Click;
btnReg.Click += this.btnReg_Click;
}
}
}
First, I think you should use ExecuteNonQuery() instead of ExecuteReader().
You call ExecuteReader() when you execute a sql command that returns something (such as SELECT).
When you call a command that doesn't return anything (such as INSERT, UPDATE, DELETE, etc.), you should call ExecuteNonQuery().
See the details here.
Second, I think you should check the result before alert "successfully". ExecuteNonQuery() returns the number of rows affected, you can check this to determine success or not.

Database is locked. insert operation

I have no idea what to do anymore with this code. I did review the opening and closing of my connections and I think all connections are okay.
I have to tables here that I'm trying to insert data. The imf table and the imf_products table. My goal is as soon as I have inserted data to my imf table I should insert data again to my imf_products.
This is 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;
using System.Data.SQLite;
namespace Natasha_POS
{
public partial class m2 : Form
{
public SQLiteConnection con = new SQLiteConnection(#"Data Source=default.db");
public m2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (combo_compname.Text.Length <= 0)
{
MessageBox.Show("Please specify the company name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_artname.Text.Length <= 0)
{
MessageBox.Show("Please specify the product name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_color.Text.Length <= 0)
{
MessageBox.Show("Please specify the product color.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (combo_size.Text.Length <= 0)
{
MessageBox.Show("Please specify the product size.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (textBox8.Text.Length <= 0)
{
MessageBox.Show("Please specify the product price.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (box_numeric.Text.Length <= 0)
{
MessageBox.Show("Please specify the number of products you're acquiring.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
dGrid.Rows.Add(combo_artname.Text,
combo_color.Text,
combo_size.Text,
Convert.ToInt32(box_numeric.Value),
Convert.ToInt32( textBox8.Text),
combo_discount.Text,"","",
Convert.ToInt32(combo_artname.SelectedValue),
Convert.ToInt32(combo_color.SelectedValue),
Convert.ToInt32(combo_size.SelectedValue),
Convert.ToInt32(combo_discount.SelectedValue)
);
////new
combo_compname.Text = "--Select Company--";
combo_cat.Text = "--Select Category--";
combo_artname.Text = "--Select Product--";
combo_color.Text = "--Select Color--";
combo_size.Text = "--Select Size--";
textBox8.Clear();
box_numeric.Value = 0;
combo_custno.Focus();
}
}
private void m2_Load(object sender, EventArgs e)
{
dateTimePicker.Enabled = false;
box_custname.Text = null;
SQLiteConnection conn1 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt = new DataTable();
conn1.Open();
SQLiteCommand cmd = conn1.CreateCommand();
cmd.CommandText = "SELECT * from customer";
SQLiteDataAdapter adapter = new SQLiteDataAdapter(cmd);
adapter.Fill(dt);
combo_custno.DataSource = dt;
combo_custno.ValueMember = "cp_id";
combo_custno.DisplayMember = "customer_no";
combo_custno.Text = "--Select Customer--";
/*IList<string> CustNo = new List<string>();
foreach (DataRow row in dt.Rows)
{
CustNo.Add(row.Field<string>("cp_id"));
}
combo_custno.Items.AddRange(CustNo.ToArray<string>());
combo_custno.AutoCompleteMode = AutoCompleteMode.Suggest;
combo_custno.AutoCompleteSource = AutoCompleteSource.ListItems; */
conn1.Close();
SQLiteConnection conn2 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt2 = new DataTable();
conn2.Open();
SQLiteCommand cmd2 = conn2.CreateCommand();
cmd2.CommandText = "SELECT * from company";
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd2);
adapter2.Fill(dt2);
combo_compname.DataSource = dt2;
combo_compname.ValueMember = "company_id";
combo_compname.DisplayMember = "company_name";
combo_compname.Text = "--Select Company--";
conn2.Close();
SQLiteConnection conn3 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt3 = new DataTable();
conn3.Open();
SQLiteCommand cmd3 = conn3.CreateCommand();
cmd3.CommandText = "SELECT category_id, category_name FROM category";
SQLiteDataAdapter adapter3 = new SQLiteDataAdapter(cmd3);
adapter3.Fill(dt3);
combo_cat.DataSource = dt3;
combo_cat.ValueMember = "category_id";
combo_cat.DisplayMember = "category_name";
combo_cat.Text = "--Select Category--";
conn3.Close();
SQLiteConnection conn4 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt4 = new DataTable();
conn4.Open();
SQLiteCommand cmd4 = conn4.CreateCommand();
cmd4.CommandText = "SELECT * FROM colors";
SQLiteDataAdapter adapter4 = new SQLiteDataAdapter(cmd4);
adapter4.Fill(dt4);
combo_color.DataSource = dt4;
combo_color.ValueMember = "color_id";
combo_color.DisplayMember = "color_name";
combo_color.Text = "--Select Color--";
conn4.Close();
SQLiteConnection conn5 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt5 = new DataTable();
conn5.Open();
SQLiteCommand cmd5 = conn5.CreateCommand();
cmd5.CommandText = "SELECT * FROM discount";
SQLiteDataAdapter adapter5 = new SQLiteDataAdapter(cmd5);
adapter5.Fill(dt5);
combo_discount.DataSource = dt5;
combo_discount.ValueMember = "discount_id";
combo_discount.DisplayMember = "discount_name";
combo_discount.Text = "";
conn5.Close();
//this.reportViewer1.RefreshReport();
}
private void combo_custno_SelectedIndexChanged(object sender, EventArgs e)
{
// int x = Convert.ToInt32(combo_custno.Text);
//////////textboxes
SQLiteConnection conn4 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt4 = new DataTable();
conn4.Open();
SQLiteCommand cmd4 = conn4.CreateCommand();
cmd4.CommandText = "SELECT * FROM customer where cp_id = '" + combo_custno.SelectedValue + "'";
SQLiteDataReader dr = cmd4.ExecuteReader();
if (dr.Read())
{
//string fname = Convert.ToString(dr["firstname"]);
//string mname = Convert.ToString(dr["firstname"]);
box_custname.Text = Convert.ToString(dr["firstname"]) + " " + Convert.ToString(dr["middlename"]) + " " + Convert.ToString(dr["lastname"]);
box_mse.Text = Convert.ToString(dr["msediscount"]);
box_nfc.Text = Convert.ToString(dr["nfcdiscount"]);
box_rating.Text = Convert.ToString(dr["rating"]);
box_avcredline.Text = Convert.ToString(dr["available_credit_line"]);
}
conn4.Close();
}
private void combo_cat_SelectedIndexChanged(object sender, EventArgs e)
{
//int x = Convert.ToInt32(combo_cat.Text);
SQLiteConnection conn2 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt2 = new DataTable();
conn2.Open();
SQLiteCommand cmd2 = conn2.CreateCommand();
cmd2.CommandText = "SELECT * FROM product where category_id = '" + combo_cat.SelectedValue+ "'";
SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(cmd2);
adapter2.Fill(dt2);
combo_artname.DataSource = dt2;
combo_artname.ValueMember = "product_id";
combo_artname.DisplayMember = "product_name";
combo_artname.Text = "--Select Product--";
conn2.Close();
SQLiteConnection conn3 = new SQLiteConnection(#"Data Source=default.db");
DataTable dt3 = new DataTable();
conn3.Open();
SQLiteCommand cmd3 = conn3.CreateCommand();
cmd3.CommandText = "SELECT * FROM size where category_id = '" + combo_cat.SelectedValue + "'";
SQLiteDataAdapter adapter3 = new SQLiteDataAdapter(cmd3);
adapter3.Fill(dt3);
combo_size.DataSource = dt3;
combo_size.ValueMember = "size_id";
combo_size.DisplayMember = "size_name";
combo_size.Text = "--Select Size--";
conn3.Close();
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void inserttoSO(string custno)
{
con.Open();
SQLiteCommand cmd = con.CreateCommand();
cmd.Parameters.AddWithValue("#custno", combo_custno.Text);
cmd.Parameters.AddWithValue("#date", dateTimePicker.Value);
//cmd.Parameters.AddWithValue("#comment", box_commment.Text);
cmd.CommandText = "INSERT INTO sales_order (customer_no,date) VALUES (#custno,#date)";
cmd.ExecuteNonQuery();
con.Close();
}
private void button3_Click(object sender, EventArgs e)
{
//inserttoSO(combo_custno.Text);
var results = MessageBox.Show("Are you sure you want to generate this inventory report?",
"Inventory report is successfully made.",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question);
if (results == DialogResult.Yes)
{
inserttoSO(combo_custno.Text);
string StrQuery = "";
using (SQLiteConnection conn = new SQLiteConnection(#"Data Source=default.db"))
{
using (SQLiteCommand cmd1 = new SQLiteCommand())
{
cmd1.Connection = conn;
conn.Open();
for (int i = 0; i < dGrid.Rows.Count; i++)
{
/*"INSERT INTO imf_products(imf_id, company_id,product_id, color_id,size_id,price,qty) VALUES (1,1,1,1,1,1,1)";*/
//(SELECT max(imf_id) FROM imf) StrQuery
cmd1.CommandText =
"INSERT INTO orders(salesorder_id, product_id, quantity,price,cash, discount_id) VALUES ((SELECT max(salesorder_id) FROM sales_order),'"
+ dGrid.Rows[i].Cells["product_id"].Value + "', '" + dGrid.Rows[i].Cells["qty"].Value + "', '"
+ dGrid.Rows[i].Cells["price"].Value + "', '" + dGrid.Rows[i].Cells["cash"].Value + "', '"
+ dGrid.Rows[i].Cells["discount_id"].Value + "')";
// cmd.CommandText = StrQuery;
cmd1.ExecuteNonQuery();
MessageBox.Show("Sales report is successfully made.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
// conn.Close();
}
}
}
else
{ MessageBox.Show("Inventory report is not made.", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
}
private void textBox8_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar)
&& !char.IsDigit(e.KeyChar)
&& e.KeyChar != '.' && e.KeyChar != ',')
{
e.Handled = true;
}
//check if '.' , ',' pressed
char sepratorChar = 's';
if (e.KeyChar == '.' || e.KeyChar == ',')
{
// check if it's in the beginning of text not accept
if (textBox8.Text.Length == 0) e.Handled = true;
// check if it's in the beginning of text not accept
if (textBox8.SelectionStart == 0) e.Handled = true;
// check if there is already exist a '.' , ','
if (alreadyExist(textBox8.Text, ref sepratorChar)) e.Handled = true;
//check if '.' or ',' is in middle of a number and after it is not a number greater than 99
if (textBox8.SelectionStart != textBox8.Text.Length && e.Handled == false)
{
// '.' or ',' is in the middle
string AfterDotString = textBox8.Text.Substring(textBox8.SelectionStart);
if (AfterDotString.Length > 2)
{
e.Handled = true;
}
}
}
//check if a number pressed
if (Char.IsDigit(e.KeyChar))
{
//check if a coma or dot exist
if (alreadyExist(textBox8.Text, ref sepratorChar))
{
int sepratorPosition = textBox8.Text.IndexOf(sepratorChar);
string afterSepratorString = textBox8.Text.Substring(sepratorPosition + 1);
if (textBox8.SelectionStart > sepratorPosition && afterSepratorString.Length > 1)
{
e.Handled = true;
}
}
}
}
private bool alreadyExist(string _text, ref char KeyChar)
{
if (_text.IndexOf('.') > -1)
{
KeyChar = '.';
return true;
}
if (_text.IndexOf(',') > -1)
{
KeyChar = ',';
return true;
}
return false;
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
dateTimePicker.Enabled = false;
}
private void groupBox1_Enter(object sender, EventArgs e)
{
}
private void button4_Click(object sender, EventArgs e)
{
inserttoSO(combo_custno.Text);
}
}
}

Categories

Resources