DataGridView not updating display after insert - c#

private void button1_Click(object sender, EventArgs e)
{
try
{
if (transaction_idTextBox.Text == "" || lastnameTextBox.Text == "" || firstnameTextBox.Text == "" || middlenameTextBox.Text == "" || txtYear.Text == "" || txtDoI.Text == "" || txtPoI.Text == "" || txtAddress.Text == "" || CB_Sex.Text == "" || txtCS.Text == "" || txtDoB.Text == "" || txtPoB.Text == "" || txtAmount.Text == "")
{
MessageBox.Show("All Fields Are Compulsory");
}
else
{
SqlCommand cmdinsert = new SqlCommand("Insert into [Transaction] values( ' " + transaction_idTextBox.Text + " ','" + lastnameTextBox.Text + "','" + firstnameTextBox.Text + " ','" + middlenameTextBox.Text + "','" + txtYear.Text + "','" + txtDoI.Text + "','" + txtPoI.Text + "','" + txtAddress.Text + "','" + CB_Sex.Text + "','" + txtCS.Text + "','" + txtDoB.Text + "','" + txtPoI.Text + "','" + txtAmount.Text + "' )", con);
con.Open();
cmdinsert.CommandType = CommandType.Text;
cmdinsert.ExecuteNonQuery();
MessageBox.Show("Data Added");
transactionDataGridView.Update();
transactionDataGridView.Refresh();
transaction_idTextBox.Text = "";
lastnameTextBox.Text = "";
firstnameTextBox.Text = "";
middlenameTextBox.Text = "";
txtYear.Text = "";
txtDoI.Text = "";
txtPoI.Text = "";
txtAddress.Text = "";
CB_Sex.Text = "";
txtCS.Text = "";
txtDoB.Text = "";
txtPoB.Text = "";
txtAmount.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}

For first : Add "LoadData();" at the end of Your code
Secondly add this to populate DataGridView:
public void LoadDataEQ()
{
DataTable AllDataTable = new DataTable();
string SqlCommand = "SELECT * FROM Transaction";
SqlDataAdapter SQLDA = new SqlDataAdapter(SqlCommand , con);
SQLDA.Fill(AllDataTable);
SQLDA.Dispose();
dataGridView1.DataSource = AllDataTable;
}

Related

Insert data into MS Access using c# with class

I wanted to insert data to microsoft access using c# and need to use class.
I've tried removing some textbox and look for some error and I feel that there might be some mistake in IF condition.
private void registerbutton_Click(object sender, EventArgs e)
{
-- CLASS --
RegStudent reg = new RegStudent();
reg.stdfname = fnametextbox.Text;
reg.stdlname = lnametextbox.Text;
reg.username = usernametextbox.Text;
reg.password = passwordtextbox.Text;
reg.dob = dobtextbox.Text;
reg.city = citytextbox.Text;
reg.state = statetextbox.Text;
reg.email = emailtextbox.Text;
reg.phoneno = ctcnotextbox.Text;
reg.phoneno2 = ctcnotextbox2.Text;
reg.course = coursetextbox.Text;
reg.emergencyname = emergencynametextbox.Text;
reg.emergencyphoneno = emergencynumbertextbox.Text;
reg.registerdate = registerdatetextbox.Text;
if (tptextbox.Text != "" && fnametextbox.Text != "" && lnametextbox.Text != "" && dobtextbox.Text != "" && usernametextbox.Text != "" && passwordtextbox.Text != "" && citytextbox.Text != "" && statetextbox.Text != "" && registerdatetextbox.Text != "" && emailtextbox.Text != "" && ctcnotextbox.Text != "" && ctcnotextbox2.Text != "" && coursetextbox.Text != "" && emergencynametextbox.Text != "" && emergencynumbertextbox.Text != "")
{
registerconnection.Open();
OleDbCommand insert = new OleDbCommand();
insert.Connection = registerconnection;
insert.CommandText = "Insert into StudentDatabase values (" + reg.stdfname + "','" + reg.stdlname + "','" + reg.username + "','" + reg.password + "','" + reg.dob + "','" + reg.city + "','" + reg.state + "','" + reg.email + "','" + reg.phoneno + "','" + reg.phoneno2 + "','" + reg.course + "','" + reg.emergencyname + "','" + reg.emergencyphoneno + ");";
insert.CommandType = CommandType.Text;
insert.Connection = registerconnection;
insert.ExecuteNonQuery();
MessageBox.Show("Data Have Been Registered.");
}
else
{
MessageBox.Show("error");
}
}
I expected that the output will be that the data will be saved.

get row with same id but different value and display different value into different label asp.net

this work but i want to display if value exist, so user can see the value username and last_update in each label based on each process_id but they have same request_id. this code only display username and last_update for the one that based on username login only.how i can do that ?
using(SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["MESTrans"].ConnectionString))
{
//bool exists = false;
int exists;
con.Open();
foreach (GridViewRow row in GridView2.Rows)
{
int req_id = Convert.ToInt32(GridView2.DataKeys[row.RowIndex].Values[0]);
using (SqlCommand cmd = new SqlCommand("select count(*) from [CutPanelConfirmation] where req_id=#req_id and process_id=#process_id", con))
{
cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString());
cmd.Parameters.AddWithValue("#req_id", req_id);
exists = (int)cmd.ExecuteScalar();
}
if (exists > 0)
{
query = "select * from CutPanelConfirmation where req_id=#req_id and process_id=#process_id";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString());
cmd.Parameters.AddWithValue("#req_id", req_id);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if ((string)dr["process_id"] == "marker")
{
LabelNameMarker.Text = LabelNameMarker.Text + " " + dr[1].ToString();
LabelDateMarker.Text = LabelDateMarker.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "fabric")
{
LabelNameFabric.Text = LabelNameFabric.Text + " " + dr[1].ToString();
LabelDateFabric.Text = LabelDateFabric.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "cutting")
{
LabelNameCutting.Text = LabelNameCutting.Text + " " + dr[1].ToString();
LabelDateCutting.Text = LabelDateCutting.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "SPP")
{
LabelNameSPP.Text = LabelNameSPP.Text + " " + dr[1].ToString();
LabelDateSPP.Text = LabelDateSPP.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "kitting")
{
LabelNameKitting.Text = LabelNameKitting.Text + " " + dr[1].ToString();
LabelDateKitting.Text = LabelDateKitting.Text + " " + dr[3].ToString();
}
if ((string)dr["process_id"] == "sew")
{
LabelNameSew.Text = LabelNameSew.Text + " " + dr[1].ToString();
LabelDateSew.Text = LabelDateSew.Text + " " + dr[3].ToString();
}
}
dr.Close();
}
con.Close();
}
}
posting [https://stackoverflow.com/users/7892938/nfh][NFH] answer
i just delete#process id from this query and it works as what i want! :
query = "select * from CutPanelConfirmation where req_id=#req_id and process_id=#process_id"; cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("#process_id", Session["process_id"].ToString()); cmd.Parameters.AddWithValue("#req_id", req_id); SqlDataReader dr = cmd.ExecuteReader();

Error SQL syntax in the middle of a textbox

When i click the insert button, my program always tell me that i have a SQL syntax error near CPF, but the error starts in the middle of the textbox, just as i write 190.890.567-45 in the text box and the program tells me that the error is near '567-45', here is the code:
private void btninserir_Click(object sender, EventArgs e)
{
string sql;
int numero;
sql = "select * from doador where CPF = " + txtCPF.Text;
DataTable dt = bd.executarconsulta(sql);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Doador já cadastrado!!!!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
if (txtNome.Text != "" || txtCel.Text != "" || txtCPF.Text != "" || txtEndereco.Text != "" || txtTelRe.Text != "" || int.TryParse(txtIdade.Text, out numero))
{
bd.ConectarBD();
sql = "INSERT INTO DOADOR(CPF, NOME, IDADE, TELCASA, TELCELULAR, ENDERECO) VALUES('" + txtCPF.Text + "','" + txtNome.Text + "'," + txtIdade.Text + ",'" + txtTelRe.Text + "','" + txtCel.Text + "','" + txtEndereco.Text + "')";
bd.executarcomandos(sql);
MessageBox.Show("Doador Cadastro com sucesso!!!!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Valor Invalido!!!!", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtCPF.BackColor = Color.Red;
txtNome.BackColor = Color.Red;
txtEndereco.BackColor = Color.Red;
txtIdade.BackColor = Color.Red;
txtTelRe.BackColor = Color.Red;
txtCel.BackColor = Color.Red;
txtCPF.Focus();
}
}
}
Error message
Just add 'between text param in SQL. Like this:
sql = "select * from doador where CPF = '" + txtCPF.Text + "'";

error insert query after install application

i testing my program and when runed in vs without any error execute !
this is my code :
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conect = new OleDbConnection();
conect.ConnectionString = "provider=microsoft.jet.oledb.4.0;" + "data source=university.mdb;Jet OLEDB:Database Password=sa#a";
conect.Open();
OleDbCommand o1 = new OleDbCommand();
o1.Connection = conect;
if(button1.Text=="save")
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
else
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteNonQuery();
if (button1.Text != "save")
{
if (o1.ExecuteScalar() == null)
MessageBox.Show("wrong user");
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
}
else
{
groupBox1.Visible = false;
menuStrip1.Visible = true;
}
conect.Close();
}
but when execute after install app and run this query error occurs :
http://s4.picofile.com/file/8184692692/qq.png
any query select without error executed but query insert or delete occurs this error
please help me
You can't use NonQuery with a "Select". Try this
if(button1.Text=="save")
{
o1.CommandText = "insert into check_user(name_user,pw_user)values('" + textBox1.Text + "','" + textBox2.Text + "')";
o1.ExecuteNonQuery();
}
else
{
o1.CommandText = " select * from check_user WHERE (name_user = '" + textBox1.Text + "') and (pw_user = '" + textBox2.Text + "' )";
o1.ExecuteQuery();
}​

how to sort searched records in a gridview

I am sorting all records successfully by implementing the following functions.
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
private void SortGridView(string sortExpression, string direction)
{
// You can cache the DataTable for improving performance
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}
public DataSet GetData()
{
SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS; Initial Catalog=PIMS; Integrated Security=true;");
{
using (SqlCommand cmd = new SqlCommand())
{
String sql = "select * from dbo.Documents1";
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
DataSet ds = new DataSet();
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(ds);
}
return ds;
}
}
}
I am having problem sorting the searched records. Code i am applying is as following :
protected void GridView2_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView1(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView1(sortExpression, ASCENDING);
}
}
private void SortGridView1(string sortExpression, string direction)
{
DataTable dt = SearchTable().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView2.DataSource = dv;
GridView2.DataBind();
}
public DataSet SearchTable()
{
string sql1 = "SELECT * from dbo.Documents1";
bool flag = false;
if (!txtRef.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Ref LIKE N'%" + txtRef.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Ref LIKE N'%" + txtRef.Text + "%'";
}
}
if (!txtSubject.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Subject LIKE N'%" + txtSubject.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Subject LIKE N'%" + txtSubject.Text + "%'";
}
}
if (!ddlSource.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Src =N'" + ddlSource.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Src =N'" + ddlSource.Text + "'";
}
}
if (!ddlDestination.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Dst=N'" + ddlDestination.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Dst =N'" + ddlDestination.Text + "'";
}
}
if (!ddlMedium.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Medium =N'" + ddlMedium.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Medium =N'" + ddlMedium.Text + "'";
}
}
if (!txtDatePrinted.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Date_Printed =N'" + txtDatePrinted.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Date_Printed =N'" + txtDatePrinted.Text + "'";
}
}
if (!txtDateReceived.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Date_Received =N'" + txtDateReceived.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Date_Received =N'" + txtDateReceived.Text + "'";
}
}
if (!ddlDocumentType.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Document_Type =N'" + ddlDocumentType.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Document_Type =N'" + ddlDocumentType.Text + "'";
}
}
if (!txtDueDate.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Due_Date = N'" + txtDueDate.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Due_Date =N'" + txtDueDate.Text + "'";
}
}
if (!txtActualDate.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Actual_Date= N'" + txtActualDate.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Actual_Date=N'" + txtActualDate.Text + "'";
}
}
if (!txtContent.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Content=N'" + txtContent.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Content=N'" + txtContent.Text + "'";
}
}
if (!txtTag.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Tag =N'" + txtTag.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Tag =N'" + txtTag.Text + "'";
}
}
if (!txtIssue.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Issue_No = N'" + txtIssue.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Issue_No = N'" + txtIssue.Text + "'";
}
}
if (!txtNotes.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Notes = N'" + txtNotes.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Notes = N'" + txtNotes.Text + "'";
}
}
if (!ddlAssignedTo.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Assigned_To = N'" + ddlAssignedTo.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Assigned_To = N'" + ddlAssignedTo.Text + "'";
}
}
if (!txtReplyRef.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Reply_Ref LIKE N'%" + txtReplyRef.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Reply_Ref LIKE N'%" + txtReplyRef.Text + "%'";
}
}
if (!ddlPriority.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Priority = N'" + ddlPriority.Text + "'";
flag = true;
}
else
{
sql1 = sql1 + " and Priority = N'" + ddlPriority.Text + "'";
}
}
if (!ddlStatus.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Status LIKE N'%" + ddlStatus.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Status LIKE N'%" + ddlStatus.Text + "%'";
}
}
if (!ddlResponse.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Response LIKE N'%" + ddlResponse.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Response LIKE N'%" + ddlResponse.Text + "%'";
}
}
if (!txtPhysicalFileNo.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Physical_File_No LIKE N'%" + txtPhysicalFileNo.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Physical_File_No LIKE N'%" + txtPhysicalFileNo.Text + "%'";
}
}
if (!txtPhysicalRackLocation.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " where Physical_Rack_Location LIKE N'%" + txtPhysicalRackLocation.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Physical_Rack_Location LIKE N'%" + txtPhysicalRackLocation.Text + "%'";
}
}
using (SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS;Initial Catalog=PIMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = sql1 + ";";
//cmd.CommandType = CommandType.StoredProcedure;
con.Open();
//dataset object to get all select statement results
DataSet ds = new DataSet();
//sql dataadoptor to fill dataset
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(ds);
}
if (con.State == ConnectionState.Open)
{
con.Close();
}
return ds;
}
}
}
Above code is sorting the searched records in Gridview2, but when it binds the records, it is binding all the records from the database table ... while I need only the searched records to be binded and shown. I cant understand where I am going wrong. Any help will be much appreciated. Thanks in advance.
Please change your searchTable function query like this.
string sql1 = "SELECT * from dbo.Documents1 where 1=1";
bool flag = false;
if (!txtRef.Text.Equals(""))
{
if (flag == false)
{
sql1 = sql1 + " and Ref LIKE N'%" + txtRef.Text + "%'";
flag = true;
}
else
{
sql1 = sql1 + " and Ref LIKE N'%" + txtRef.Text + "%'";
}
}
You need not to put "where" in every if condition you need to add condition with "and" keyword.

Categories

Resources