How to add a cache clean to my program - c#

Here is the my c# application, it's a pop up ,i want to know how add cache clean method to this code.
i want to include a cache clean coding to clean cache in this program and minimize the ram
namespace SmartAlert
{
public partial class Form2 : Form
{
static String maxValue = "1";
static int checkNewRecordTime =8;
static int frameVisibilityTime = 20;
private const int CP_DISABLE_CLOSE_BUTTON = 0x200;
System.Windows.Forms.Timer hideTime;
public Form2()
{
InitializeComponent();
checkNewRecordTimer();
checkNewRecord();
}
// Method to disable form close button \\
protected override CreateParams CreateParams
{
get
{
CreateParams cp = base.CreateParams;
cp.ClassStyle = cp.ClassStyle | CP_DISABLE_CLOSE_BUTTON;
return cp;
}
}
protected override void OnLoad(EventArgs e)
{
// Code for set the screen location \\
var screen = Screen.FromPoint(this.Location);
this.Location = new Point(screen.WorkingArea.Right - this.Width, screen.WorkingArea.Bottom - this.Height);
base.OnLoad(e);
}
private void Form2_Load(object sender, EventArgs e)
{
}
// Database record's checking method \\
// 2
public void checkNewRecord()
{
try {
var connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection scon = new SqlConnection(connectionString);
String cost_code = ConfigurationManager.AppSettings["costCenter"].ToString();
scon.Open();
SqlCommand smd = new SqlCommand();
DateTime d1 = DateTime.Now;
string sqlFormattedDate = d1.Date.ToString("yyyy-MM-dd");
//** query for check and get the last enterd record **\\
smd.CommandText = "select max(OrdM_No) as M_id from FOOrderMaster where OrdM_Staff ='" + cost_code + "' and OrdM_Date ='" + sqlFormattedDate + "' ";
smd.Connection = scon;
SqlDataReader reader = smd.ExecuteReader();
reader.Read();
string mx_id = reader["M_id"].ToString();
reader.Close();
if (maxValue != mx_id)
{
maxValue = mx_id;
popup_Window(mx_id);
this.Show();
frameHideTimer();
}
scon.Close();
}
catch (SqlException)
{
}
catch (Exception)
{
}
}
// Retriving Database record's checking and sending to form method \\
// 3
public void popup_Window(String mx_id)
{
try
{
var connectionString = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection scon1 = new SqlConnection(connectionString);
scon1.Open();
//** query for get the data of last enterd record **\\
SqlCommand smd1 = new SqlCommand();
smd1.CommandText = "SELECT f.OrdM_No,f.OrdM_BillNo,f.OrdM_Table,f.OrdM_Date,d.OrdD_Price FROM FOOrderMaster f inner join FOOrderDetail d on f.OrdM_No = d.OrdM_No WHERE f.OrdM_No = '" + mx_id + "'";
smd1.Connection = scon1;
SqlDataReader reader12 = smd1.ExecuteReader();
reader12.Read();
if (reader12.HasRows)
{
label8.Text = reader12["OrdM_BillNo"].ToString();
label9.Text = reader12["OrdD_Price"].ToString();
label7.Text = reader12["OrdM_Table"].ToString();
string nm = reader12["OrdM_Date"].ToString();
DateTime dm = Convert.ToDateTime(nm);
string df = dm.Date.ToString("yyyy-MM-dd");
label6.Text = df.ToString();
}
scon1.Close();
}
catch (SqlException)
{
}
catch (Exception)
{
}
}
// timer for check new record method \\
// 1
public void checkNewRecordTimer()
{
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 1000*checkNewRecordTime; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
}
void timer_Tick(object sender, EventArgs e)
{
checkNewRecord();
}
// timer for hidden the form \\
public void frameHideTimer()
{
hideTime = new System.Windows.Forms.Timer();
hideTime.Interval = 1000*frameVisibilityTime; // specify interval time as you want
hideTime.Tick += new EventHandler(hideTimer_Tick);
hideTime.Start();
}
void hideTimer_Tick(object sender, EventArgs e)
{
this.Hide();
hideTime.Stop();
}
private void button1_Click(object sender, EventArgs e)
{
var fm3 = new Form3();
fm3.Show();
}
private void Form2_Move(object sender, EventArgs e)
{
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
var fm3 = new Form3();
fm3.Show();
notifyIcon1.Visible = true;
}
}
}
please help me with this

Related

What should I do if I want the value of the dgv1(datagridview) to be shown on a different form?

Form1
namespace erpmam
{
public partial class Form1 : Form
{
MySqlDB mySqlDB;
SqlDataAdapter adpt;
DataTable dt;
SqlConnection con;
public void showdata()
{
adpt = new SqlDataAdapter("select deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms from sys_department;",con);
dt = new DataTable();
adpt.Fill(dt);
dgv1.DataSource = dt;
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
mySqlDB = new MySqlDB("server=······");
}
private SqlDataAdapter MySqlDataAdapter(string v, MySqlConnection con)
{
throw new NotImplementedException();
}
public void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void BTN_INSERT_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ShowDialog();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_id like '%" + textBox1.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
string sql = "";
sql += " select";
sql += " deptmt_id, deptmt_name, deptmt_seq, reg_ymdtms, mod_ymdtms";
sql += " from sys_department";
sql += " where deptmt_name like '%" + textBox2.Text.Trim() + "%'";
DataTable dt = mySqlDB.ExecuteReader(sql, mySqlDB.DBConnection());
dgv1.SuspendLayout();
dgv1.Rows.Clear();
for (int idx = 0; idx < dt.Rows.Count; idx++)
{
DataRow r = dt.Rows[idx];
dgv1.Rows.Add(1);
dgv1[0, idx].Value = r["deptmt_id"].ToString().Trim();
dgv1[1, idx].Value = r["deptmt_name"].ToString().Trim();
dgv1[2, idx].Value = r["deptmt_seq"].ToString().Trim();
dgv1[3, idx].Value = r["reg_ymdtms"].ToString().Trim();
dgv1[4, idx].Value = r["mod_ymdtms"].ToString().Trim();
}
dgv1.ResumeLayout();
}
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e)
{
Form3 Form3 = new Form3();
Form3.ShowDialog();
}
}
}
Form2
namespace erpmam
{
public partial class Form2 : Form
{
MySqlConnection connection = new MySqlConnection("datasource =······");
MySqlCommand command;
public Form2()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
}
public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
string insertQuery = "INSERT INTO sys_department(DEPTMT_ID, DEPTMT_NAME, DEPTMT_SEQ, REG_YMDTMS) VALUES(" + textBox1.Text + ',' + textBox2.Text + ','+ textBox3.Text + ','+ "NOW()" +")";
connection.Open();
MySqlCommand command = new MySqlCommand(insertQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Form3
namespace erpmam
{
public partial class Form3 : Form
{
MySqlConnection connection = new MySqlConnection("datasource = localhost; port = 3306; Initial Catalog = 'erp'; username = root; password=610822");
MySqlCommand command;
public Form3()
{
InitializeComponent();
}
public void executeMyQuery(string query)
{
try
{
openConnection();
command = new MySqlCommand(query, connection);
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("Query Executed");
}
else
{
MessageBox.Show("Query Not Executed");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
closeConnection();
}
} public void openConnection()
{
if (connection.State == ConnectionState.Closed)
{
connection.Open();
}
}
public void closeConnection()
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
private void btn_update_Click(object sender, EventArgs e)
{
string updateQuery = " UPDATE sys_department";
updateQuery += " SET DEPTMT_NAME = '" + textBox2.Text + "', DEPTMT_SEQ = '" + textBox3.Text + "', mod_ymdtms = NOW()";
updateQuery += " where DEPTMT_ID = '" + textBox1.Text + "'";
connection.Open();
MySqlCommand command = new MySqlCommand(updateQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("changed normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_delete_Click(object sender, EventArgs e)
{
string deleteQuery = " DELETE from sys_department";
deleteQuery += " where DEPTMT_ID = '" + textBox1.Text + "' or DEPTMT_NAME = '" + textBox2.Text + "' or DEPTMT_SEQ = '" + textBox3.Text + "'" ;
connection.Open();
MySqlCommand command = new MySqlCommand(deleteQuery, connection);
try
{
if (command.ExecuteNonQuery() == 1)
{
MessageBox.Show("adding normally");
}
else
{
MessageBox.Show("error");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
connection.Close();
this.Close();
}
private void btn_cancel_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Simply you can create a Global variable of Datatable to use it as source of Data and you can use it anywhere in your Forms
This is the GLobal Class
//make sure to import this System.Data
using System.Data;
class Global
{
private static DataTable source;
public static DataTable Source
{
get
{
// Reads are usually simple
return source;
}
set
{
// You can add logic here for race conditions,
// or other measurements
source = value;
}
}
}
In your first form
string connectString = "datasource=xxxx;port=3306;username=xxxx;password=;database=xxxxx;";
MySqlConnection conn;
MySqlCommand comm;
MySqlDataReader read;
MySqlDataAdapter adapter;
Global mySource;
void getData() {
string query = "Select * from tableName";
conn = new MySqlConnection(connectString);
conn.Open();
comm = new MySqlCommand(query, conn);
adapter = new MySqlDataAdapter(query, conn);
DataSet ds = new DataSet();
adapter.Fill(ds);
//setting up
Global.Source = ds.Tables[0];
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
In you second Form
public Form2()
{
InitializeComponent();
dataGridView1.DataSource = Global.Source;
}
Simply you can create static method in the class of form3 and accept one argument from DataGridView type and call this method from form1 and pass dg1 after filling it with rows then you can access it now from this static method...
private void dgv1_CellClick(object sender, DataGridViewCellEventArgs e) {
Form3 Form3 = new Form3();
Form3.staticMethodToPassDGVBetweenTwoForms(dgv1);
Form3.ShowDialog();
}
namespace erpmam {
public partial class Form3 : Form {
public Form3() {
initializeComponent();
}
public static void staticMethodToPassDGVBetweenTwoForms(DataGridView dgv1){
//do anything with dg1 now
}
}

pass checked datagridview rows from child form to main form datagridview

I have 2 forms
ApodeikseisTimologion
EggrafesTimologionEsodon
ApodeikseisTimologion is the main form and EggrafesTimologionEsodon is the childform and 1 datagridview (dataGridViewProionApodeixeisTimologiouEsodon and dataGridViewEggrafesProionParastikouEsodon) in each form.
DataGridViewProionApodeixeisTimologiouEsodon belongs to main form and dataGridViewEggrafesProionParastikouEsodon belongs to child form.
Now, I want to pass the checked values from the child form to parent form without losing the values that i have already put in other textboxes in parent form.
Here is my code:
Form ApodeikseisTimologion.
I use this to open the child form
private void LinkLblEisagogiEggrafon_Click(object sender, EventArgs e) {
EggrafesTimologionEsodon eggrTimolEsodon = new EggrafesTimologionEsodon(cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text);
eggrTimolEsodon.ShowDialog();
this.Refresh();
}
Form EggrafesTimologionEsodon
private void EggrafesTimologionEsodon_Load(object sender, EventArgs e) {
try {
con = new SqlConnection();
con = DBAccess.Conn;
con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou inner join Parastatiko on ProionParastatikou.ParastatikoID = Parastatiko.ParastatikoID" +
" where ProionParastatikou.Ypoloipo > 0.00 and Parastatiko.Eponimia = '" + txtPelatisId.Text + "'", con);
ds = new System.Data.DataSet();
adap.Fill(ds, "BsProionParastatikouEsodon");
dataGridViewEggrafesProionParastikouEsodon.DataSource = ds.Tables[0];
con.Close();
}
catch (Exception ex) {
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally {
if (MyConn.State != ConnectionState.Closed)
MyConn.Close();
}
}
I have this image :
in the child form i also have this to check the rows from the checkbox column of the datagridview and stored them to a list to transfer them to the parent form without losing the other data that i have already.
private void BtnProsthikiEggrafon_Click(object sender, EventArgs e) {
ApodeixeisTimologion apo = new ApodeixeisTimologion(null);
List<Int64> lst2send = new List<Int64>();
Int64 toSend;
foreach (DataGridViewRow eggrafes in dataGridViewEggrafesProionParastikouEsodon.Rows) {
if (Convert.ToBoolean(eggrafes.Cells["CheckBoxColumn"].Value)) {
int RowIndexCheck = eggrafes.HeaderCell.RowIndex;
Int64.TryParse(dataGridViewEggrafesProionParastikouEsodon.Rows[RowIndexCheck].Cells["proionParastatikouIDDataGridViewTextBoxColumn"].Value.ToString(),out toSend);
lst2send.Add(toSend);
}
}
apo.AfterProsthikiProionParastatikou(null, null, lst2send);
//apo.Refresh();
this.Close();
}
When the child form close, I have that in parent Form:
public void AfterProsthikiProionParastatikou(object sender,EventArgs e,IList<Int64> lst) {
String csvLst = string.Empty;
int count = 0;
foreach ( Int64 lstItems in lst) {
if (count == 0) {
csvLst = lstItems.ToString();
count += 1;
}
else {
csvLst = csvLst + "," + lstItems.ToString();
}
}
_con = new SqlConnection();
_con = DBAccess.Conn;
_con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou where" +
" ProionParastatikou.Ypoloipo > 0.00 and ProionParastatikou.ProionParastatikouID"+
" in( " + csvLst + ")", _con);
ds = new System.Data.DataSet();
adap.Fill(ds, "bsProionApodeixeisTimologiouEsodon");//
dataGridViewProionApodeixeisTimologiouEsodon.DataSource = ds.Tables["bsProionApodeixeisTimologiouEsodon"];
//dataGridViewProionApodeixeisTimologiouEsodon.Refresh();
_con.Close();
}
i make a breakpoint in
ds = new System.Data.DataSet();
adap.Fill(ds, "bsProionApodeixeisTimologiouEsodon");//
dataGridViewProionApodeixeisTimologiouEsodon.DataSource = ds.Tables["bsProionApodeixeisTimologiouEsodon"];
And i see that the ds fills with the correct values but rows are not coming in the dataGridViewProionApodeixeisTimologiouEsodon which is the grid in parent form.
In all the forms i am using datasets and bindingSources in datagrids, and the datagrids are bounded except of the checkbox column.
Can somebody helps.
If someone needs more help i will give it.
Here's a minimal, but working sample.
Have a public property on your Form2, and access it from Form1. My snippet is passing a string, but yours will be dealing with a different data type. Same concept, different data type.
Form1.cs
using System;
using System.Windows.Forms;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += Button1_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2("blah blah blah");
f2.ShowDialog();
label1.Text = f2.returnValue;
}
}
}
Form2.cs
using System;
using System.Windows.Forms;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form2 : Form
{
public string returnValue;
private string submittedString { get; set; }
public Form2(string incomingString)
{
InitializeComponent();
submittedString = incomingString;
button1.Click += Button1_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
returnValue = "I'd rather show you my value instead of yours(" + submittedString + ")...";
this.Close();
}
}
}
Working with Grid types
Form1.cs
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form1 : Form
{
BindingList<gridentry> gridList = new BindingList<gridentry>();
DataGridView dgv = new DataGridView();
DataGridView gridViewForTheReturnedRows;
public Form1()
{
InitializeComponent();
initializeGrid();
addDataToGridSource("name1");
addDataToGridSource("name2");
addDataToGridSource("name3");
addDataToGridSource("name4");
button1.Click += Button1_Click;
}
private void addDataToGridSource(string incomingString)
{
gridList.Add(new gridentry { col1 = incomingString, col2 = incomingString + "in col2", col3 = incomingString + "in col3" });
}
private void initializeGrid()
{
dgv.Location = new System.Drawing.Point(this.Location.X + 5, this.Location.Y + 5);
this.Controls.Add(dgv);
dgv.AutoGenerateColumns = true;
dgv.DataSource = gridList;
}
private void Button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2(dgv);
f2.ShowDialog();
if (f2.returnRows != null && f2.returnRows.Count > 0)
{
gridViewForTheReturnedRows = new DataGridView();
gridViewForTheReturnedRows.ColumnCount = f2.returnRows[0].Cells.Count;
gridViewForTheReturnedRows.Rows.InsertRange(0, f2.returnRows.ToArray());
gridViewForTheReturnedRows.Location = new System.Drawing.Point(10, dgv.Location.Y + dgv.Height + 5);
this.Controls.Add(gridViewForTheReturnedRows);
}
}
}
public class gridentry
{
public string col1 { get; set; }
public string col2 { get; set; }
public string col3 { get; set; }
}
}
Form2.cs
using System;
using System.Windows.Forms;
using System.Collections.Generic;
namespace PassParamsFromForm2ToForm1_45997869
{
public partial class Form2 : Form
{
public DataGridView returnGrid = new DataGridView();
public List<DataGridViewRow> returnRows { get; set; }
private DataGridView submittedGrid { get; set; }
public Form2(DataGridView incomingGrid)
{
InitializeComponent();
submittedGrid = incomingGrid;
submittedGrid.Location = new System.Drawing.Point(this.Location.X + 5, this.Location.Y + 5);
Controls.Add(submittedGrid);
button1.Click += Button1_Click;
}
private void Button1_Click(object sender, EventArgs e)
{
returnGrid = submittedGrid;//if you want to return the grid
//returning rows
/*
* You'll need your own mechanism to differentiate between
*/
bool rowIsModified = false;
returnRows = new List<DataGridViewRow>();
foreach (DataGridViewRow item in submittedGrid.Rows)
{
if (item.Index % 2 != 0)
{
rowIsModified = true;
}
if (rowIsModified)
{
DataGridViewRow r = (DataGridViewRow)item.Clone();
for (int i = 0; i < item.Cells.Count; i++)
{
r.Cells[i].Value = item.Cells[i].Value;
}
returnRows.Add(r);
}
}
this.Close();
}
}
}
Form ApodeikseisTimologion. I use this to open the child form
private void LinkLblEisagogiEggrafon_Click(object sender, EventArgs e)
{
if (cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text == "")
{
MessageBox.Show("Πρέπει να επιλέξετε Πελάτη", "Προειδοποίηση");
}
else
{
EggrafesTimologionEsodon eggrTimolEsodon = new EggrafesTimologionEsodon(cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text);//p
eggrTimolEsodon.ShowDialog();
listToFill = eggrTimolEsodon.lst2send;
AfterProsthikiProionParastatikou(null,null,listToFill);
//AfterProsthikiProionParastatikou(null);
//this.Refresh();
}
}
Form EggrafesTimologionEsodon
private void EggrafesTimologionEsodon_Load(object sender, EventArgs e)
{
//CmbBoxPelatis.SelectedIndex = -1;
//EggrafesTimologionEsodon values = new EggrafesTimologionEsodon();
try
{
con = new SqlConnection();
con = DBAccess.Conn;
con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou inner join Parastatiko on ProionParastatikou.ParastatikoID = Parastatiko.ParastatikoID" +
" where ProionParastatikou.Ypoloipo > 0.00 and Parastatiko.Eponimia = '" + txtPelatisId.Text + "'", con);
ds = new System.Data.DataSet();
adap.Fill(ds, "BsProionParastatikouEsodon");
dataGridViewEggrafesProionParastikouEsodon.DataSource = ds.Tables[0];
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (MyConn.State != ConnectionState.Closed)
MyConn.Close();
}
}
From that I am having the image which is on top.
public List<Int64> lst2send;
private void BtnProsthikiEggrafon_Click(object sender, EventArgs e)
{
lst2send = new List<Int64>();
Int64 toSend;
foreach (DataGridViewRow eggrafes in dataGridViewEggrafesProionParastikouEsodon.Rows)
{
if (Convert.ToBoolean(eggrafes.Cells["CheckBoxColumn"].Value))
{
int RowIndexCheck = eggrafes.HeaderCell.RowIndex;
Int64.TryParse(dataGridViewEggrafesProionParastikouEsodon.Rows[RowIndexCheck].Cells["proionParastatikouIDDataGridViewTextBoxColumn"].Value.ToString(),out toSend);
lst2send.Add(toSend);
}
}
this.Close();
}
When the child form close, I have that in parent Form:
public List<Int64> listToFill;
public void AfterProsthikiProionParastatikou(object sender, EventArgs e, IList<Int64> lst)//object sender,EventArgs e,
{
String csvLst = string.Empty;
int count = 0;
foreach ( Int64 lstItems in lst)
{
if (count == 0)
{
csvLst = lstItems.ToString();
count += 1;
}
else
{
csvLst = csvLst + "," + lstItems.ToString();
}
}
_con = new SqlConnection();
_con = DBAccess.Conn;
_con.Open();
adap = new SqlDataAdapter("select ProionParastatikou.* from ProionParastatikou where" +
" ProionParastatikou.Ypoloipo > 0.00 and ProionParastatikou.ProionParastatikouID"+
" in( " + csvLst + ")", _con);
DataSetApodeixeisTimologiouEsodon ds = new DataSetApodeixeisTimologiouEsodon();
adap.Fill(ds.ApodeixeisProionParastatiko);//
bsProionApodeixeisTimologiouEsodon.DataSource = ds.ApodeixeisProionParastatiko;// Tables[0];
dataGridViewProionApodeixeisTimologiouEsodon.DataSource = bsProionApodeixeisTimologiouEsodon;
_con.Close();
}
private void LinkLblEisagogiEggrafon_Click(object sender, EventArgs e)
{
if (cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text == "")
{
MessageBox.Show("Πρέπει να επιλέξετε Πελάτη", "Προειδοποίηση");
}
else
{
EggrafesTimologionEsodon eggrTimolEsodon = new EggrafesTimologionEsodon(cmbBoxEponimiaPelatiApodeixeisTimologiouEsodon.Text);//p
eggrTimolEsodon.ShowDialog();
listToFill = eggrTimolEsodon.lst2send;
AfterProsthikiProionParastatikou(null,null,listToFill);
//AfterProsthikiProionParastatikou(null);
//this.Refresh();
}
}
And I am having the results that I want
enter image description here

Inherit Datatable object

I'm working at a C# solution, and I've got this form which I'm populating my txtboxes, using a DataTable object and then retrieving the information trought the row number, the problem is, I've got navigation buttons, next and previous, and I just noticed that when I call my function to PopulateView(); after I press this buttons, I redo the DB connection, the SQLite query and the datatable fill.
I feel ashamed but, I really don't know where is the proper place to put this function in order that my other functions in this form receive these objects.
My Code:
namespace X_Project{
public partial class Cad_Prod : Form
{
System.Data.SQLite.SQLiteConnection conn1 = new System.Data.SQLite.SQLiteConnection("data source=X.s3db");
int prodstart = 0;
public Cad_Prod()
{
InitializeComponent();
}
public void Cad_Prod_Load(object sender, EventArgs e)
{
}
private void PopulateView()
{
string query = "SELECT * FROM Cad_Prod";
string query2 = "SELECT * FROM Cat";
try
{
using (SQLiteCommand comm = new SQLiteCommand(query, conn1))
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm))
using (SQLiteCommand comm2 = new SQLiteCommand(query2, conn1))
using (SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(comm2))
{
conn1.Open();
DataTable produtos = new DataTable();
adapter.Fill(produtos);
DataTable categoria = new DataTable();
adapter2.Fill(categoria);
int auxCat = int.Parse(produtos.Rows[prodstart].ItemArray[4].ToString()) - 1;
txtProdutoNome.Text = produtos.Rows[prodstart].ItemArray[1].ToString();
txtProdutoPreco.Text = produtos.Rows[prodstart].ItemArray[2].ToString();
txtProdutoQtd.Text = produtos.Rows[prodstart].ItemArray[3].ToString();
cbbCategoria.Text = categoria.Rows[auxCat].ItemArray[1].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnAvancar_Click(object sender, EventArgs e)
{
prodstart = prodstart + 1;
PopulateView();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
prodstart = prodstart - 1;
PopulateView();
}
}
the code above works, but no the way I want it, what i really would like to do is:
namespace X_Project\
{
public partial class Cad_Prod : Form
{
System.Data.SQLite.SQLiteConnection conn1 = new System.Data.SQLite.SQLiteConnection("data source=X.s3db");
int prodstart = 0;
public Cad_Prod()
{
InitializeComponent();
}
public void Cad_Prod_Load(object sender, EventArgs e)
{
string query = "SELECT * FROM Cad_Prod";
string query2 = "SELECT * FROM Cat";
try
{
using (SQLiteCommand comm = new SQLiteCommand(query, conn1))
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm))
using (SQLiteCommand comm2 = new SQLiteCommand(query2, conn1))
using (SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(comm2))
{
conn1.Open();
DataTable produtos = new DataTable();
adapter.Fill(produtos); // I would like this to be inherited
DataTable categoria = new DataTable();
adapter2.Fill(categoria); // I would like this to be inherited
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void PopulateView()
{
int auxCat = int.Parse(produtos.Rows[prodstart].ItemArray[4].ToString()) - 1;
txtProdutoNome.Text = produtos.Rows[prodstart].ItemArray[1].ToString();
txtProdutoPreco.Text = produtos.Rows[prodstart].ItemArray[2].ToString();
txtProdutoQtd.Text = produtos.Rows[prodstart].ItemArray[3].ToString();
cbbCategoria.Text = categoria.Rows[auxCat].ItemArray[1].ToString();
}
private void btnAvancar_Click(object sender, EventArgs e)
{
prodstart = prodstart + 1;
PopulateView();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
prodstart = prodstart - 1;
PopulateView();
}
}
Place the dataTables in form level property variables that use the "Lazy initializer" pattern, i.e., where they are coded so they will only call the database once, and populate a static private variable with the datatable that first time; every successive call will just read the private variable and skip the database call.
public partial class Cad_Prod : Form
{
private static readonly SQLiteConnection conn1 =
new SQLiteConnection(("data source=X.s3db");
private static DataTable produtos;
private static DataTable produtos;
private static DataTable AutoDataTable =>
produtos?? (produtos = GetAutos());
private static DataTable CategoryDataTable =>
categoria ?? (categoria = GetCategories());
int prodstart = 0;
public Cad_Prod() { InitializeComponent(); }
public void Cad_Prod_Load(object sender, EventArgs e) { }
private static DataTable GetAutos()
{
string query = "SELECT * FROM Cad_Prod";
try
{
using (SQLiteCommand comm = new SQLiteCommand(query, conn1))
using (SQLiteDataAdapter adapter = new SQLiteDataAdapter(comm))
{
conn1.Open();
DataTable produtos = new DataTable();
adapter.Fill(produtos);
return produtos;
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro",
MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
private static DataTable GetCategories()
{
string query2 = "SELECT * FROM Cat";
try
{
using (SQLiteCommand comm2 = new SQLiteCommand(query2, conn1))
using (SQLiteDataAdapter adapter2 = new SQLiteDataAdapter(comm2))
{
conn1.Open();
DataTable categoria = new DataTable();
adapter2.Fill(categoria);
return categoria;
}
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Erro",
MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
}
private void PopulateView()
{
int auxCat = int.Parse(produtos.Rows[prodstart]
.ItemArray[4].ToString()) - 1;
txtProdutoNome.Text = produtos.Rows[prodstart]
.ItemArray[1].ToString();
txtProdutoPreco.Text = produtos.Rows[prodstart]
.ItemArray[2].ToString();
txtProdutoQtd.Text = produtos.Rows[prodstart]
.ItemArray[3].ToString();
cbbCategoria.Text = categoria.Rows[auxCat]
.ItemArray[1].ToString();
}
private void btnAvancar_Click(object sender, EventArgs e)
{
prodstart = prodstart + 1;
PopulateView();
}
private void btnVoltar_Click(object sender, EventArgs e)
{
prodstart = prodstart - 1;
PopulateView();
}
}

Disable controls from another form

I have two forms. One is MainForm which is an MDI parent and has a ToolStripFile that is set to enabled = false at the MainForm load, and the other form is form2 which is an MDI child and serves as my login form. If login is successful, the ToolStripFile should be enabled = true. I have this code but it doesn't work:
private void btnLogin_Click(object sender, EventArgs e)
{
MainForm mf = new MainForm();
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "SELECT * FROM Employees WHERE Username = #Username AND Passcode = #Passcode";
command.Parameters.AddWithValue("#Username", txtUsername.Text);
command.Parameters.AddWithValue("#Passcode", txtPassword.Text);
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
Employees emp = new Employees();
//emp.MdiParent = this.MdiParent;
//emp.Show();
mf.ToolStripFile.enabled = true;
this.Dispose();
}
if (count > 1)
{
MessageBox.Show("There is a duplicate in username and password.");
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex, "LOGIN");
}
finally
{
connection.Close();
}
}
You are creating a new instance of your main form. You actually need to use the instance of the current form using MDIParent property.
You can use something like this in parent form:
public bool EnableButton
{
set
{
button1.Enabled = value;
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
MDIChild child = new MDIChild();
child.MdiParent = this;
child.Show();
}
In your child form, you can do something like this:
private void button1_Click(object sender, EventArgs e)
{
// if successful
(MdiParent as MDIParent).EnableButton = true;
}

Connection error C#

private OleDbConnection conexao;
private Timer time = new Timer();
public void Conexao() //Conexão
{
string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|DB.accdb";
conexao = new OleDbConnection(strcon);
}
void tabela()
{
Conexao();
conexao.Open();
label1.Text = DateTime.Now.ToString();
string bn = "select D2 from Planilha where D2='" + label1.Text + "'";
textBox1.Text = label1.Text;
OleDbCommand Queryyy = new OleDbCommand(bn, conexao);
OleDbDataReader drr;
drr = Queryyy.ExecuteReader();
if (drr.Read() == true)
{
try
{
MessageBox.Show("Hi");
}
catch (OleDbException ex)
{
MessageBox.Show("" + ex);
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tabela();
}
Timer Interval = 1000
(click for larger view)
I'm all afternoon trying to fix it but could not so I come here for help
I think asawyer's comment had it right I bet the problem is from the fact you are not handling your objects correctly, get rid of your class objects and work with using statements
public OleDbConnection Conexao() //Conexão
{
string strcon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|DB.accdb";
return new OleDbConnection(strcon);
}
void tabela()
{
try
{
timer1.Enabled = false;
using(var conexao = Conexao())
{
conexao.Open();
label1.Text = DateTime.Now.ToString();
string bn = "select D2 from Planilha where D2='" + label1.Text + "'";
textBox1.Text = label1.Text;
using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
using(OleDbDataReader drr = Queryyy.ExecuteReader())
{
if (drr.Read() == true)
{
try
{
MessageBox.Show("Hi");
}
catch (OleDbException ex)
{
MessageBox.Show("" + ex);
}
}
}
}
}
finally
{
timer.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
tabela();
}
Also from the fact that you are only reading the first column of the first row, you should use ExecuteScalar instead of ExecuteReader.
using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
try
{
var result = Queryyy.ExecuteScalar();
if (result != null)
{
MessageBox.Show("Hi");
}
}
catch (OleDbException ex)
{
MessageBox.Show("" + ex);
}
}
}
You also should be using parametrized queries.
label1.Text = DateTime.Now.ToString();
string bn = "select D2 from Planilha where D2=#param1";
textBox1.Text = label1.Text;
using(OleDbCommand Queryyy = new OleDbCommand(bn, conexao))
{
Queryyy.Parameters.AddWithValue("#param1", label1.Text);
//....

Categories