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();
}
}
Related
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);
}
}
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?
Form 1 and 2
how do i auto select after i click search from another form ?
iam using C#. the textbox below only for store(check) i want the form 1 with gridview is selected
my code below on form 2 :
private void simpleButton1_Click(object sender, EventArgs e)
{
cari();
}
public void cari()
{
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
ds.Tables.Clear();
command.Connection = myConnection;
command.CommandText = "select * from General.genre WHERE genre Like '%"+textEdit1.Text.ToString()+"%' or code like '%"+textEdit1.Text+"%'";
myConnection.Open();
var buka = command.ExecuteReader();
if (buka.Read())
{
textEdit2.Text = buka[1].ToString();
}
else
{
MessageBox.Show("type genre");
}
// MessageBox.Show("kebaca");
}
catch (System.Exception ex)
{
MessageBox.Show("error" + ex);
}
myConnection.Close();
}
dataGrid.SelectedRows.Clear();
foreach(DataGridViewRow row in dataGrid.Rows)
{
if(YOUR CONDITION)
row.Selected = true;
}
I made an application who updates a sqlce database.
The problem is, when I try to delete something it says "InvalidArgument=Value of '1' is not valid for 'index'."
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.SqlServerCe;
namespace Database_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SqlCeConnection conn = new SqlCeConnection(#"Data Source=C:\automail.sdf");
////////////////////////////////////Methodes////////////////////////////////////
private void Populate()
{
SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails ORDER BY principalID", conn);
listView1.Items.Clear();
try
{
SqlCeDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
ListViewItem it = new ListViewItem(dr["principalID"].ToString());
it.SubItems.Add(dr["query"].ToString());
it.SubItems.Add(dr["email"].ToString());
it.SubItems.Add(dr["subject"].ToString());
listView1.Items.Add(it);
}
dr.Close();
dr.Dispose();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
////////////////////////////////////Methodes////////////////////////////////////
// Insert button (for data insert)
private void button1_Click(object sender, EventArgs e)
{
if ( txtEmail.Text == "" || txtQuery.Text == "")
{
MessageBox.Show("Fill in all the information first!");
}
else
{
SqlCeCommand cmd = new SqlCeCommand("INSERT INTO Emails(principalID, email, query, subject) VALUES(#principalID, #email, #query, #subject)", conn);
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#principalID", txtPrincipal.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#query", txtQuery.Text);
cmd.Parameters.AddWithValue("#subject", txtSubject.Text);
try
{
int affectedrows = cmd.ExecuteNonQuery();
if (affectedrows > 0)
{
Populate();
MessageBox.Show("Email added successfully!");
txtEmail.Clear();
txtPrincipal.Clear();
txtQuery.Clear();
txtSearch.Clear();
txtSubject.Clear();
}
else
{
MessageBox.Show("Failed to add email!");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
//if form shown fill the listview with the new information of the database
private void Form1_Shown(object sender, EventArgs e)
{
try
{
conn.Open();
Populate();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
Application.ExitThread();
}
}
//open form 2 and hide this
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
//if listview selected enable button, else disable
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
//enable delete button
button3.Enabled = true;
ListViewItem itm = listView1.SelectedItems[0];
string principalid = itm.SubItems[0].Text;
string query = itm.SubItems[1].Text;
string email = itm.SubItems[2].Text;
string subject = itm.SubItems[3].Text;
txtPrincipal.Text = principalid.ToString();
txtEmail.Text = email.ToString();
txtQuery.Text = query.ToString();
txtSubject.Text = subject.ToString();
}
else
{
button3.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
}
//delete record button
private void button3_Click_1(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count <= 0)
{
MessageBox.Show("Select a record!");
}
else
{
ListView.SelectedListViewItemCollection items = this.listView1.SelectedItems;
//for (int i = 0; i < listView1.SelectedItems.Count; i++)
foreach(ListViewItem item in items)
{
SqlCeCommand cm = new SqlCeCommand("DELETE * FROM Emails WHERE query ='" + listView1.SelectedItems[1].Text + "'", conn);
try
{
cm.ExecuteNonQuery();
Populate();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
// if button clicked, transfer information out of the records selected to form2
private void button2_Click_1(object sender, EventArgs e)
{
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to close this application?\nThis will terminate all systems which are active at the moment","Close", MessageBoxButtons.YesNo);
if (result == DialogResult.Yes)
{
}
if (result == DialogResult.No)
{
e.Cancel = true;
}
}
private void button4_Click(object sender, EventArgs e)
{
//try
//{
// SqlCeCommand cm = new SqlCeCommand("SELECT * FROM Emails where principalID like " + txtSearch.Text, conn);
//}
//catch (Exception ex)
//
// MessageBox.Show(ex.Message);
//}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
}
}
}
It throws the error at
SqlCeCommand cm = new SqlCeCommand("DELETE * FROM Emails WHERE query ='" + listView1.SelectedItems[1].Text + "'", conn);
Can someone help me please? I've already tried with parameters, but still no luck...
It worked fine before I imported an CSV file into my database with a tool, but the database structure is still the same, so it should be able to delete everything I select.
You can not use * with where condition in delete command ..so TRY like this....
SqlCeCommand cm = new SqlCeCommand("DELETE FROM Emails WHERE query ='" + listView1.SelectedItems[0].Text + "'", conn);
Ignoring the other issues in your code (security of your Sql, etc), I believe this is the specific problem you're asking about.
You're using this:
listView1.SelectedItems[1].Text
... but arrays and lists in C# are zero-absed, and so the first selected item is actually this:
listView1.SelectedItems[0].Text
It's also worth noting that, since you call this in a loop, you will try to delete this single item once for every item in the list. I suspect the loop is redundant or, alternatively, your commented out loop (through each selected item) is what you really want, and in that case you mean this:
listView1.SelectedItems[i].Text
... which would use the text of each item in turn as you loop.