I want to check the database table from txtSearch by entering barcode with txtSearch_TextChanged event, and after the txtSearch_TextChanged event I want to select all txtSearch text, it is work as well when the barcode is correct, also I would like to select all txtSearch when the barcode is not correct.
private void txtSearch_TextChanged(object sender, EventArgs e)
{
try
{
String _pcode;
double _price;
double _qty;
cn.Open();
cm = new SqlCommand("select * from tblProduct where barcode like '" + txtSearch.Text + "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
_pcode = dr["pcode"].ToString();
_price = double.Parse(dr["price"].ToString());
_qty = double.Parse(txtQty.Text);
dr.Close();
cn.Close();
AddToCart(_pcode, _price, _qty);
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = txtSearch.Text.Length;
}
else
{
dr.Close();
cn.Close();
}
}
catch (Exception ex)
{
cn.Close();
MessageBox.Show(ex.Message);
}
}
Does it work when I type any barcode that it is in tblProduct and the all text from txtSearch will be selected , I want to the text from txtSearch will be Selected when any barcode is not in the tblProduct, I try this else { dr.Close(); cn.Close(); txtSearch.SelectionStart = 0; txtSearch.SelectionLength = txtSearch.Text.Length; } it just select the first number, and I haven seen any error yet from the code.
private void txtSearch_TextChanged(object sender, EventArgs e)
{
try
{
// Your code
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
txtSearch.TextChanged -= txtSearch_TextChanged;
txtSearch.Text = txtSearch.Tag + txtSearch.Text;
txtSearch.Tag = txtSearch.Text;
txtSearch.SelectionStart = 0;
txtSearch.SelectionLength = txtSearch.Text.Length;
txtSearch.TextChanged += txtSearch_TextChanged;
}
private void txtSearch_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Back:
//remove last character from txtSearch.Tag
txtSearch.Tag = txtSearch.Tag != null && !string.IsNullOrWhiteSpace(txtSearch.Tag.ToString())
? txtSearch.Tag.ToString().Remove(txtSearch.Tag.ToString().Length - 1)
: string.Empty;
break;
case Keys.Delete:
txtSearch.Tag = string.Empty;
break;
// handle other keys here
}
}
here is the solutions, thank you for your time
private void txtSearch_TextChanged(object sender, EventArgs e)
{
try
{
if (txtSearch.Text.Trim().Length == 1)
{
tmrDelay.Enabled = true;
tmrDelay.Start();
tmrDelay.Tick += new EventHandler(tmrDelay_Tick);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void tmrDelay_Tick(object sender, EventArgs e)
{
try
{
tmrDelay.Stop();
string strCurrentString = txtSearch.Text.Trim().ToString();
if (strCurrentString != "")
{
String _pcode;
double _price;
double _qty;
cn.Open();
cm = new SqlCommand("select * from tblProduct where barcode like '" + txtSearch.Text + "'", cn);
dr = cm.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
_pcode = dr["pcode"].ToString();
_price = double.Parse(dr["price"].ToString());
_qty = double.Parse(txtQty.Text);
dr.Close();
cn.Close();
AddToCart(_pcode, _price, _qty);
}
else
{
MessageBox.Show("soory the bar code does not exist", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
dr.Close();
cn.Close();
txtSearch.Text = "";
}
txtSearch.Focus();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Related
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
}
}
I'm making a small program that allows me to insert data into a data table which is connected with PostgreSQL. All functions are working fine on postgresql: select, insert, update and delete.
Here is the code:
private void FrmTeachers_Load(object sender, EventArgs e)
{
conn = new NpgsqlConnection(connstring);
Select();
//dgvTabela.Columns["docente_id"].HeaderText = "Teachers ID";
}
private void Select()
{
try
{
conn.Open();
sql = #"select * from docen_selecionar()";
cmd = new NpgsqlCommand(sql, conn);
dt = new DataTable();
dt.Load(cmd.ExecuteReader());
conn.Close();
dgvTabela.DataSource = null;
dgvTabela.DataSource = dt;
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Error: " + ex.Message);
}
}
private void DgvTabela_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
txtName.Text = dgvTabela.Rows[e.RowIndex].Cells["_docente_id"].Value.ToString();
txtID.Text = dgvTabela.Rows[e.RowIndex].Cells["_nome_docente"].Value.ToString();
txtVAT.Text = dgvTabela.Rows[e.RowIndex].Cells["_nif_number"].Value.ToString();
txtDepart.Text = dgvTabela.Rows[e.RowIndex].Cells["_departamento"].Value.ToString();
txtDegree.Text = dgvTabela.Rows[e.RowIndex].Cells["_grau_academico"].Value.ToString();
}
}
private void btnRegister_Click(object sender, EventArgs e)
{
rowIndex = -1;
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = true;
txtName.Text = txtDegree.Text = txtDepart.Text = txtID.Text = txtVAT.Text = null;
txtName.Select();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (rowIndex < 0)
{
MessageBox.Show("Please choose a Teacher to update");
return;
}
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = true;
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (rowIndex < 0)
{
MessageBox.Show("Please choose a Teacher ID to delete");
return;
}
try
{
conn.Open();
sql = #"select * from docen_apagar(:_docente_id)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_docente_id", int.Parse(dgvTabela.Rows[rowIndex].Cells["docente_id"].Value.ToString()));
if ((int)cmd.ExecuteScalar() == 1)
{
MessageBox.Show("Teacher deleted successfully");
rowIndex = -1;
Select();
}
conn.Close();
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Delete fail. Please try again. Error:" + ex.Message);
}
}
//save - esqueci-me de alterar o name
private void iconButton1_Click(object sender, EventArgs e)
{
int result = 0;
if (rowIndex < 0) //insert
{
try
{
conn.Open();
sql = #"select * from docen_registar(:_docente_id,:_nome_docente,:_departmento,:_grau_academico,:_nif_number)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_nome_docente", txtName.Text);
cmd.Parameters.AddWithValue("_docente_id", txtID.Text);
cmd.Parameters.AddWithValue("_departamento", txtDepart.Text);
cmd.Parameters.AddWithValue("_grau_academico", txtDegree.Text);
cmd.Parameters.AddWithValue("_nif_number", txtVAT.Text);
result = (int)cmd.ExecuteScalar();
conn.Close();
if (result == 1)
{
MessageBox.Show("Inserted new Teacher successfully");
Select();
}
else
{
MessageBox.Show("Inserted fail");
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Inserted fail, please try again. Error: " + ex.Message);
}
}
else //update
{
try
{
conn.Open();
sql = #"select * from docen_update(:_docente_id,:_nome_docente,:_departmento,:_grau_academico,:_nif_number)";
cmd = new NpgsqlCommand(sql, conn);
cmd.Parameters.AddWithValue("_docente_id", int.Parse(dgvTabela.Rows[rowIndex].Cells["docente_id"].Value.ToString()));
cmd.Parameters.AddWithValue("_nome_docente", txtName.Text);
cmd.Parameters.AddWithValue("_docente_id", txtID.Text);
cmd.Parameters.AddWithValue("_departamento", txtDepart.Text);
cmd.Parameters.AddWithValue("_grau_academico", txtDegree.Text);
cmd.Parameters.AddWithValue("_nif_number", txtVAT.Text);
result = (int)cmd.ExecuteScalar();
conn.Close();
if (result == 1)
{
MessageBox.Show("Successfully updated");
Select();
}
else
{
MessageBox.Show("Updated fail, please try again.");
}
}
catch (Exception ex)
{
conn.Close();
MessageBox.Show("Updated fail, please try again. Error: " + ex.Message);
}
}
result = 0;
txtName.Text = txtDegree.Text = txtDepart.Text = txtID.Text = txtVAT.Text = null;
txtName.Enabled = txtDegree.Enabled = txtDepart.Enabled = txtID.Enabled = txtVAT.Enabled = false;
}
}
}
I'm trying to create 4 buttons: insert, update, delete and save and when I click save it gives the following error:
"Error: 42601 syntax error at or near ":""
I Really don't know what it is.
Can someone help me?
I want when I enter the bar-code number without pressing any buttons automatically the data show up,and the quantity be 1 by default i tried the same with txt_no but it needs to press the enter button also.
here is the form.enter image description here
and here is the code:
private void txtno_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
txtqty.Enabled = true;
txtqty.Focus();
}
}
private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
try
{
string txt="Select * from products where id = '"+txtno.Text+"'";
MySqlCommand cmd = new MySqlCommand(txt,con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
int price = int.Parse(txtqty.Text.Trim()) * int.Parse(r[4].ToString());
totalprice = totalprice + price;
dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);
}
lbitems.Text = "" + (dataGridView1.RowCount - 1) + "";
lbtotal.Text = "" + totalprice + "";
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error From Database");
}
txtno.Focus();
txtno.Clear();
txtqty.Enabled = false;
txtqty.Clear();
}
}
You need TextChanged event handler for txtno(i.e. Bar-code textbox).
Add TextChanged event handler for txtno as below.
And as suggested by #HansKesting, you should sanitize inputs to avoid sql injection.
private void txtno_TextChanged(object sender, KeyPressEventArgs e)
{
if(!string.IsNullOrEmpty(txtno.Text))
{
txtqty.Enabled = true;
txtqty.Focus();
Search();
}
else
{
txtqty.Enabled = false;
}
}
private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
Search();
}
}
private void Search()
{
try
{
string txt = "Select * from products where id = '" + txtno.Text + "'";
MySqlCommand cmd = new MySqlCommand(txt, con);
con.Open();
MySqlDataReader r = cmd.ExecuteReader();
while (r.Read())
{
int price = int.Parse(txtqty.Text.Trim()) * int.Parse(r[4].ToString());
totalprice = totalprice + price;
dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);
}
lbitems.Text = "" + (dataGridView1.RowCount - 1) + "";
lbtotal.Text = "" + totalprice + "";
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error From Database");
}
txtno.Focus();
txtno.Clear();
txtqty.Enabled = false;
txtqty.Clear();
}
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);
//....
im taking Some Invoice No form a table to a Dropdownlist, after select the invoice number i can take all products to the grid view, with additional , price and all,
my problem is i have to click two times to edit the row, but it is not updating, when click edit button in first row in first time , it is not working , but after click on next row,s edit button first row is enabling the edit textboxes, but not updating only empty data on the grid ...
Image
http://i.stack.imgur.com/X8W6Q.gif
in this part im taking the data to grid ..
DataTable DataTbt = new DataTable();
SqlCommand Command = new SqlCommand();
SqlDataAdapter DtaAdapter = new SqlDataAdapter();
protected void ddlInvoiceNumber_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GetReturnRecords("Invoice No", ddlInvoiceNumber.SelectedValue);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
DataTbt.Clear();
DataTbt.Dispose();
DtaAdapter.Dispose();
Command.Dispose();
Connection.Close();
}
}
private void GetReturnRecords(string searchBy, string searchVal)
{
try
{
Command = new SqlCommand("SP_SearchPurchasesLines", Connection);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("#SearchBy", searchBy);
Command.Parameters.AddWithValue("#SearchVal", searchVal);
DtaAdapter.SelectCommand = Command;
DtaAdapter.Fill(DataTbt);
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
DataTbt.Clear();
DataTbt.Dispose();
Command.Dispose();
Connection.Close();
}
}
data binding to the grid..
private void BindReturnGrid()
{
try
{
DtaAdapter = new SqlDataAdapter("SP_SearchPurchasesLines", Connection);
DtaAdapter.Fill(DataTbt);
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = null;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
DataTbt.Clear();
DataTbt.Dispose();
DtaAdapter.Dispose();
Connection.Close();
}
}
editing updating deleting row from grid...
protected void GridViewPurchaseReturn_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridViewPurchaseReturn.EditIndex = -1;
BindReturnGrid();
}
protected void GridViewPurchaseReturn_RowEditing(object sender, GridViewEditEventArgs e)
{
GridViewPurchaseReturn.EditIndex = e.NewEditIndex;
BindReturnGrid();
}
I think you need to add the bind gridview method in inside of !ISPostbak on page load event .
see this code
page-load ()
{
if(!IsPostback)
{
BindReturnGrid();
}
}
You have to modify your GridViewPurchaseReturn_RowUpdating and GridViewPurchaseReturn_RowDeleting methods to update the change:
protected void GridViewPurchaseReturn_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Your code to delete the records in db
BindReturnGrid();
}
protected void GridViewPurchaseReturn_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Your code to update the records in db
GridViewPurchaseReturn.EditIndex = -1;
BindReturnGrid();
}
EDIT: After you dispose your command and closing the connection, I think your GridView DataSource should be null. To avoid this, I would change the code like this:
//DataTable DataTbt = new DataTable();
//SqlCommand Command = new SqlCommand();
//SqlDataAdapter DtaAdapter = new SqlDataAdapter();
protected void ddlInvoiceNumber_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
GetReturnRecords("Invoice No", ddlInvoiceNumber.SelectedValue);
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
//DataTbt.Clear();
//DataTbt.Dispose();
//DtaAdapter.Dispose();
//Command.Dispose();
//Connection.Close();
}
}
private void GetReturnRecords(string searchBy, string searchVal)
{
DataTable DataTbt = new DataTable();
SqlDataAdapter DtaAdapter = new SqlDataAdapter();
try
{
SqlCommand Command = new SqlCommand("SP_SearchPurchasesLines", Connection);
Command.CommandType = CommandType.StoredProcedure;
Command.Parameters.AddWithValue("#SearchBy", searchBy);
Command.Parameters.AddWithValue("#SearchVal", searchVal);
using (Connection)
{
Connection.Open();
DtaAdapter.SelectCommand = Command;
DtaAdapter.Fill(DataTbt);
}
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", String.Format("alert('Error occured : {0}');", ex.Message), true);
}
finally
{
//DataTbt.Clear();
//DataTbt.Dispose();
//Command.Dispose();
//Connection.Close();
}
}
private void BindReturnGrid()
{
try
{
DataTable DataTbt = new DataTable();
SqlDataAdapter DtaAdapter = new SqlDataAdapter("SP_SearchPurchasesLines", Connection);
using (Connection)
{
Connection.Open();
DtaAdapter.Fill(DataTbt);
}
if (DataTbt.Rows.Count > 0)
{
GridViewPurchaseReturn.DataSource = DataTbt;
GridViewPurchaseReturn.DataBind();
}
else
{
GridViewPurchaseReturn.DataSource = null;
GridViewPurchaseReturn.DataBind();
}
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Error occured : " + ex.Message.ToString() + "');", true);
}
finally
{
//DataTbt.Clear();
//DataTbt.Dispose();
//DtaAdapter.Dispose();
//Connection.Close();
}
}