Textbox Auto Number generated in c# error - c#

I am creating a simple product form in c#. while I generated auto number getting error what I tried so far i attached below.product id starts with 00001. I created a method Getproduct() inside the method I wrote the code.error displayed syntax error.
public void Getproduct() {
string sql;
SqlConnection con = new SqlConnection("server =.; initial catalog=product; integrated security=true");
SqlDataAdapter dr;
SqlDataReader dr1;
sql = "SELECT id,product_name,product_desc,price FROM product Order By id Desc";
SqlCommand com = new SqlCommand(sql, con);
SqlDataReader dr = com.ExecuteReader();
if (dr.Read() == true) {
int id;
int pid;
id = (dr[0] + 1);
pid = id.ToString("00000");
else if IsDBNull(dr) {
pid = ("00001");
}
}
}

Try this code
public void Getproduct()
{
string sql;
SqlConnection con = new SqlConnection("server =.; initial catalog=product; integrated security=true");
SqlDataAdapter dapt;
SqlDataReader dr1;
sql = "SELECT id,product_name,product_desc,price FROM product Order By id Desc";
SqlCommand com = new SqlCommand(sql, con);
SqlDataReader dr = com.ExecuteReader();
int id;
string pid;
if (dr.Read() == true)
{
int val = 0;
Int32.TryParse(dr[0].ToString(),out val);
id = ( val + 1);
pid = id.ToString("00000");
}
else if( Convert.IsDBNull(dr) )
{
pid = ("00001");
}
}

Related

when trying to open a connection to phpmyadmin server the program freezes

I'm trying to get my application to work with the database which is online in a phpmyadmin sql server. when i start my application it needs to get the password from the database, but when it tries to open a connection the whole program just freezes and it stays like that for a long time. in each class in which i am using this i make a new connection i don't know if this could be a problem for this or not.
here underneath is the database class i am using for this.
class Database
{
private SqlConnection connection;
private string connectionstring = "Server=studmysql01.fhict.local;Uid=dbi413434;Database=dbi413434;Pwd=Koekjesdeeg;";
private string nfcId;
private int vak;
private int rij;
public Database()
{
connection = new SqlConnection(connectionstring);
}
public string GetPassword(string username)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT password FROM Login WHERE username = '" + username + "'", connection);
string checkPassWord = Convert.ToString(cmd.ExecuteScalar());
connection.Close();
return checkPassWord;
}
public void MakeAccount(string userName, string passWord)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO LOGIN (USERNAME, PASSWORD) VALUES (#USERNAME, #PASSWORD)";
comm.Parameters.AddWithValue("#USERNAME", userName);
comm.Parameters.AddWithValue("#PASSWORD", passWord);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("account is not made");
}
connection.Close();
}
public void Change_Info(double rate, int maximum_stay, int row, int line)
{
string command;
connection.Open();
SqlCommand comm = connection.CreateCommand();
if (rate == 0)
{
command = "UPDATE General SET Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
else if (maximum_stay == 0)
{
command = "UPDATE General SET Rate=#rate, Row=#row, Line=#line WHERE ID=1";
}
else if (row == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Line=#line WHERE ID=1";
}
else if (line == 0)
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row WHERE ID=1";
}
else
{
command = "UPDATE General SET Rate=#rate, Maximum_Stay=#maximum_stay, Row=#row, Line=#line WHERE ID=1";
}
comm.CommandText = command;
comm.Parameters.AddWithValue("#rate", rate);
comm.Parameters.AddWithValue("#maximum_stay", maximum_stay);
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not updated in general");
}
connection.Close();
}
public void CheckForId(int id, int row, int line, bool taken, string target)
{
string queryUpdate = "UPDATE eventlog SET Rij=#row, Vak=#line, Beschikbaarheid=#taken, Parkeerdoel=#target WHERE ID=#id";
string queryInsert = "INSERT INTO eventlog (ID, Rij, Vak, Beschikbaarheid, Parkeerdoel) VALUES (#id, #row, #line, #taken, #target)";
string queryDelete = "DELETE * FROM eventlog WHERE id=#id";
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT id FROM eventlog WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", id);
string data = Convert.ToString(cmd.ExecuteScalar());
SqlCommand comm = connection.CreateCommand();
if (data == "")
{
comm.CommandText = queryInsert;
}
else if (Int32.Parse(data) == id)
{
comm.CommandText = queryUpdate;
}
else
{
comm.CommandText = queryDelete;
}
comm.Parameters.AddWithValue("#row", row);
comm.Parameters.AddWithValue("#line", line);
comm.Parameters.AddWithValue("#taken", taken);
comm.Parameters.AddWithValue("#target", target);
comm.Parameters.AddWithValue("#id", id);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("info is not correctly inserted checkForid");
}
connection.Close();
}
public double GetRate()
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT Rate FROM General WHERE ID=1", connection);
double rate = Convert.ToDouble(cmd.ExecuteScalar());
connection.Close();
return rate;
}
public void SetId(int id, string nfcId, string kenteken, int row, int line, DateTime begintTijd)
{
if (row != -1 || line != -1)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO INCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", begintTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", row);
comm.Parameters.AddWithValue("#ParkeerVak", line);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not correctly inserted Setid");
}
connection.Close();
}
}
public void GetVisitorInformation(string kenteken)
{
connection.Open();
SqlCommand cmd = new SqlCommand("SELECT NfcId FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd2 = new SqlCommand("SELECT ParkeerVak FROM INCHECK WHERE Kenteken=#kenteken", connection);
SqlCommand cmd3 = new SqlCommand("SELECT ParkeerRij FROM INCHECK WHERE Kenteken=#kenteken", connection);
cmd.Parameters.AddWithValue("#kenteken", kenteken);
cmd2.Parameters.AddWithValue("#kenteken", kenteken);
cmd3.Parameters.AddWithValue("#kenteken", kenteken);
nfcId = Convert.ToString(cmd.ExecuteScalar());
vak = Convert.ToInt32(cmd2.ExecuteScalar());
rij = Convert.ToInt32(cmd3.ExecuteScalar());
connection.Close();
}
public void SetCheckOutId(int id, string kenteken, DateTime eindTijd)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO UITCHECK (Timestamp, NfcId, Kenteken, ParkeerRij, ParkeerVak) VALUES (#Timestamp, #NfcId, #Kenteken, #ParkeerRij, #ParkeerVak)";
comm.Parameters.AddWithValue("#Timestamp", eindTijd);
comm.Parameters.AddWithValue("#NfcId", nfcId);
comm.Parameters.AddWithValue("#Kenteken", kenteken);
comm.Parameters.AddWithValue("#ParkeerRij", rij);
comm.Parameters.AddWithValue("#ParkeerVak", vak);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("checkoutid is not correctly inserted");
}
connection.Close();
}
public void SetParkingTargets(string target)
{
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = "INSERT INTO ParkingTargets (Targets) VALUES (#Targets)";
comm.Parameters.AddWithValue("#Targets", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("parking targets are not set");
}
connection.Close();
}
public void DeleteParkingTarget(string target)
{
string queryDelete = "DELETE FROM ParkingTargets WHERE Targets=#target";
connection.Open();
SqlCommand comm = connection.CreateCommand();
comm.CommandText = queryDelete;
comm.Parameters.AddWithValue("#target", target);
if (comm.ExecuteNonQuery() == 0)
{
throw new ArgumentException("not deleted");
}
connection.Close();
}
public List<string> GetParkingTargets()
{
List<string> targets = new List<string>();
connection.Open();
SqlCommand cmd2 = new SqlCommand("SELECT COUNT(id) FROM ParkingTargets", connection);
int numberOfLines = Convert.ToInt32(cmd2.ExecuteScalar());
for (int i = 1; i <= numberOfLines; i++)
{
SqlCommand cmd = new SqlCommand("SELECT Targets FROM ParkingTargets WHERE ID=#id", connection);
cmd.Parameters.AddWithValue("#id", i);
targets.Add(Convert.ToString(cmd.ExecuteScalar()));
}
connection.Close();
return targets;
}
}

How to delete multiple rows in C# using a SQL query?

I have code for deleting a row in C# using a SqlCommand. But I want to delete multiple rows. Can anyone help me with this? I am new to C#.
This is my code - please help. Thank you in advance.
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
You can build a comma separated userid list like -
string strUserIds = string.Empty();
for(int i=0; i<dataGrid.Count;i++)
{
strUserIds = strUserIds +","+ dataGrid.SelectedRows[0].Cells[0].Value;
}
--Remove last unwanted comma from strUserIds
then execute sql query as "DELETE FROM EmployeeTbl WHERE UserID in (" + strUserIds + ")"
This will delete multiple records from table.
Just Make some changes in Your Coding !
Delete All Selected Rows
Run Your select * from ActiveUser
public void deldata()
{
foreach (DataGridViewRow dr in dataGrid1.SelectedRows)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = #"Data Source=DDBULK10\SQLEXPRESS;Initial Catalog=MasterList; Integrated Security = True";
if (dr.Index > 0)
{
int selectedIndex = dataGrid1.SelectedRows[0].Index;
int rowID = int.Parse(dataGrid1[0, selectedIndex].Value.ToString());
string sql = "DELETE FROM ActiveUser WHERE EmpId = #EmpId";
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = con;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#EmpId";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
//deleteRecord.Connection.Close();
MessageBox.Show("Record Successfully Deleted");
}
else if (dialogResult == DialogResult.No)
{
this.Refresh();
}
}
}
public void showdata()
{
SqlDataAdapter sda = new SqlDataAdapter("select * from ActiveUser", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGrid1.DataSource = dt;
}
You can use something like this; i didn't test the code but it should work if you create the parameters you need, before running code you have to create a type table, please see the link for details.
using (connection)
{
string sql ="Delete from YourTable t join #yourTypeTable i on t.id = i.Id:";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
SqlParameter tvpParam = deleteCommand.Parameters.AddWithValue("#yourTypeTable", yourIdList);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.yourTypeTable";
deleteCommand.ExecuteNonQuery();
}

InvalidOperationException exception while trying to execute an update query

private void button1_Click(object sender, EventArgs e)
{
int f = 1;
SqlConnection con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; database = 'C:\Users\Emil Sharier\Documents\testDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
con.Open();
int bal = 0;
string cmdstr = "select * from users where userid='"+ Form1.userid+"';";
cmd.CommandText = cmdstr;
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
bal = int.Parse(dr[2].ToString());
int draw = int.Parse(textBox1.Text);
if(draw > bal)
{
MessageBox.Show("Insufficient balance!");
return;
}
else
{
bal -= draw;
cmdstr = "update users set balance='"+bal.ToString()+"' where userid='"+ Form1.userid + "';";
SqlDataAdapter da = new SqlDataAdapter();
da.UpdateCommand = con.CreateCommand();
da.UpdateCommand.CommandText = cmdstr;
try
{
da.UpdateCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
f = 0;
}
if (f == 1)
MessageBox.Show("Money withdrawn succesfully!");
else
MessageBox.Show("Enter correct amount!");
}
con.Close();
}
I am getting an "InvalidOperationException" while executing this program. I am not sure what the error is. Please help.
da.UpdateCommand.ExecuteNonQuery() is not getting executed
......
var sqlcmd = new SqlCommand(cmdstr, con);
.....
try
{
sqlcmd.ExecuteNonQuery();
....
Don't use adapter.
And yes. Faster of all try to close connection and open new one for update operation.

C# - Error With Getting Data From mySQL Database

I am currently getting an error when trying to get data from mySQL:
Additional information: Could not find specified column in results: admin
My code is:
public int getLevel()
{
string sqlCommand = "Select level from users where username = 'admin'";
int value = 0;
MySqlConnection con = new MySqlConnection("host=111.222.111.222;user=MYUSERNAME;password=MYPASSWORD;database=tcg;");
MySqlCommand cmd = new MySqlCommand(sqlCommand, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
value += int.Parse(reader.GetString("admin"));
}
return value;
}
Try:
public int getLevel()
{
int value = 0;
using(MySqlConnection con = new MySqlConnection("host=45.37.80.181;user=MYUSERNAME;password=MYPASSWORD;database=tcg;"))
{
con.Open();
using(MySqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Select level from users where username = #ad";
cmd.Parameters.AddWithValue("#ad","admin");
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
value += int.Parse(reader[0]);
}
}
con.Close();
}
return value;
}
If you only have one admin, use:
public int getLevel()
{
int value = 0;
using(MySqlConnection con = new MySqlConnection("host=45.37.80.181;user=MYUSERNAME;password=MYPASSWORD;database=tcg;"))
{
con.Open();
using(MySqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "Select level from users where username = #ad";//add Order by if you need to
cmd.Parameters.AddWithValue("#ad","admin");
value += Convert.ToInt32(com.ExecuteScalar());//this assumes you will get an integer value
}
con.Close();
}
return value;
}

select statement where username is equal to session

simple question, is it possible to do this? Select Id from Table where username = Session?
SqlCommand cm = new SqlCommand("select ID from CustomerDetails Where CustomerName ="Session["New"], con); - this has been solved.
2nd question:
i want to implement it like this:
if (Session["New"] != reader["ID"].ToString())
{
Response.Redirect("NotAuthorized.aspx");
}
giving me an error in my if statement. any tricks?
Full code is here:
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string str = "select ID from CustomerDetails Where CustomerName = '"+Session["New"].ToString()+"'";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
if (!IsPostBack)
{
if (Session["New"] != reader["ID"].ToString())
{
Response.Redirect("NotAuthorized.aspx");
}
Try this
SqlCommand cm = new SqlCommand("select ID from CustomerDetails Where CustomerName ='"+Session["New"].ToString()+"'", con);
string ID =cm.ExecuteScalar().ToString();
Assuming,
Session["New"] contains username (datatype as string)
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand("select ID from CustomerDetails ", conn);
SqlDataAdapter da = new SqlDataAdapter("", conn);
DataTable dt = new DataTable();
da.fill(dt);
int count=dt.Rows.Count;
if (Count > 0)
{
for (int i = 0; i < Count; i++)
{
Label2.Text =dt1.Rows[i]["ID"].ToString();
}
}
}
To make your code more error proof I think it is better to use named parameters in your SQL command like this:
// suppose customer ID is an integer
int customerId = 0;
string customerName = (string)Session["New"];
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCmd = new SqlCommand("SELECT id FROM CustomerDetails WHERE CustomerName = #customerName", sqlCon);
sqlCmd.Parameters.AddWithValue("#customerName", customerName);
object result = sqlCmd.ExecuteScalar();
if (result != null)
customerId = (int)result;
}

Categories