My Class
public string Countryadd(string country, string id)
{
string data = "0";
try
{
string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition
SqlDataReader dr = conn.query(qry1);
if (dr.Read())
{
return data = "1";
}
else
{
string qry = "insert into Country values('" + id + "','" + country + "')";
conn.nonquery(qry);
return data = "3";
}
}
catch (Exception ex)
{
string x = ex.Message();
}
return data;
}
this string value how can we set in a label
My button_click function is
protected void Button1_Click(object sender, EventArgs e)
{
string str = mas.Countryadd(txtcountry.Text, txtid.Text);
if (str == "1")
{
Response.Write("<script>alert('Country Already Exist!!!!')</script>");
}
else if (str == "3")
{
Response.Write("<script>alert('Country Added Succesfully')</script>");
}
else
{
Label1.Text = str;
}
}
It's not the prettiest of code. Returning a string as a kind of status code is generally bad practice, because you don't know the range of possible values which can be returned, and what they mean. At the very least consider integer or even enum (which is named).
That being said, I would handle the check and the insert in separate methods, and catch the exception in the click event handler - let a single method have a single responsibility:
private void AddCountry(string country, string id)
{
using (SqlConnection conn = new SqlConnection())
{
string sql = string.Format("INSERT INTO Country (Id, Country) VALUES ('{0}', '{1}')", id, country);
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.ExecuteNonQuery();
}
}
}
private bool Exists(string country, string id)
{
using (SqlConnection conn = new SqlConnection())
{
string sql = "SELECT Count(*) FROM Country WHERE Country='" + country + "'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
int count = (int)cmd.ExecuteScalar();
return count >= 1;
}
}
}
private void Button1_Click(object sender, EventArgs e)
{
try
{
if (Exists(txtcountry.Text, txtid.Text))
{
Response.Write("<script>alert('Country Already Exist!!!!')</script>");
}
else
{
AddCountry(txtcountry.Text, txtid.Text);
Response.Write("<script>alert('Country Added Succesfully')</script>");
}
}
catch (Exception ex)
{
Label1.Text = ex.Message;
}
}
Catch(Exception e)
{
Label.Text= e.Message;
}
Related
The update is working fine, but stock value when is purchased I want to show messagebox, and stop the purchase when the value is zero in the stock update code.
I tried this code, but he only reduces value if the quantity is zero showing minus in the stock value when to stop when the value is equal to zero.
private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=#q where id=#Xkey ", con);
//stock=Convert.ToInt32(dr)
cmd.Parameters.AddWithValue("#q", newqty);
cmd.Parameters.AddWithValue("#Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
//showExpenses();
//Reset();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
The following first asserts there is sufficient stock, if not, alert caller else update the stock. This assumes no other users are working with the same item.
Note the use of delegates and that the database does not match your database but the same will work for your code with adjustments.
public class DataOperations
{
private const string ConnectionString
= "Data Source=.\\sqlexpress;Initial Catalog=NorthWind2020;Integrated Security=True";
public delegate void OnProcessing(string text);
public static event OnProcessing Processed;
public static void UpdateProductStockCount(int id, int amount)
{
using (var cn = new SqlConnection(ConnectionString))
{
using (var cmd = new SqlCommand() { Connection = cn })
{
cmd.CommandText = "SELECT UnitsInStock FROM dbo.Products WHERE ProductID = #Id";
cmd.Parameters.Add("#Id", SqlDbType.Int).Value = id;
cn.Open();
var currentCount = (short)cmd.ExecuteScalar();
if (currentCount - amount <0)
{
Processed?.Invoke("Insufficient stock");
}
else
{
cmd.CommandText = "UPDATE dbo.Products SET UnitsInStock = #InStock WHERE ProductID = #Id";
cmd.Parameters.Add("#InStock", SqlDbType.Int).Value = currentCount - amount;
cmd.ExecuteNonQuery();
Processed?.Invoke("Processed");
}
}
}
}
}
Form code
public partial class StackoverflowForm : Form
{
public StackoverflowForm()
{
InitializeComponent();
DataOperations.Processed += DataOperationsOnProcessed;
}
private void DataOperationsOnProcessed(string text)
{
if (text == "Insufficient stock")
{
MessageBox.Show($"Sorry {text} ");
}
else
{
MessageBox.Show(text);
}
}
private void updateButton_Click(object sender, EventArgs e)
{
DataOperations.UpdateProductStockCount(21,1);
}
}
As #BagusTesa suggested, a simple if could do the trick:
private void updateQty()
{
try
{
int newqty = stock - Convert.ToInt32(txtnumberofunit.Text);
if (newqty >= 0) // proceed
{
con.Open();
SqlCommand cmd = new SqlCommand("Update medic Set quantity=#q where id=#Xkey ", con);
cmd.Parameters.AddWithValue("#q", newqty);
cmd.Parameters.AddWithValue("#Xkey", key);
cmd.ExecuteNonQuery();
MessageBox.Show("Medicine updated!!");
con.Close();
}
else // cancel purchase
{
MessageBox.Show("New quantity is below 0, purchase cancelled");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is my program:
What I want to do: when I enter 1 in ProductID textbox, I want category, name and price for ProductID = 1 to be filled into their textboxes.
I have tried to read from product table where ProductID = ProductIDTB.Text and then changed the other textboxes to show the data inside the other columns
Here is my code when ProductID textbox is changed:
protected void ProductIDTB_TextChanged(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = ('" + Convert.ToInt32(ProductIDTB.Text) + "') ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
}
}
Work-around: as textbox_textchanged event was not working, I decided to add a button which finds product using the ID:
protected void FindProductBtn_Click(object sender, EventArgs e)
{
string connectionString1;
SqlConnection cnn1;
connectionString1 = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Greenwich_Butchers;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
cnn1 = new SqlConnection(connectionString1);
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = (" + Convert.ToInt32(ProductIDTB.Text) + ") ";
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
try
{
cnn1.Open();
using (SqlDataReader read = com1.ExecuteReader())
{
while (read.Read())
{
String productcategory = Convert.ToString(read["ProductCategory"]);
ProductCategoryTB.Text = productcategory;
String productname = Convert.ToString(read["ProductName"]);
ProductNameTB.Text = productname;
String productprice = Convert.ToString(read["ProductPrice"]);
ProdPriceTB.Text = productprice;
}
}
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
finally
{
cnn1.Close();
ProductCategoryTB.ReadOnly = true;
ProductNameTB.ReadOnly = true;
ProdPriceTB.ReadOnly = true;
}
}
Set the textbox's AutoPostBack attribute to true
More info: https://meeraacademy.com/textbox-autopostback-and-textchanged-event-asp-net/
<asp:TextBox ID="ProductIDTB" runat="server" AutoPostBack="True"
OnTextChanged="ProductIDTB_TextChanged"></asp:TextBox>
By the way, use SqlParameter to use parameterized query. Aside from sql-injection attack prevention, parameterized query can help the RDBMS store and re-use the execution plan of similar queries, to ensure better performance. See: https://dba.stackexchange.com/questions/123978/can-sp-executesql-be-configured-used-by-default
string selectSql1 = "SELECT * FROM [Product] WHERE ProductID = #productIdFilter";
int productIdFilter = Convert.ToInt32(ProductIDTB.Text);
SqlCommand com1 = new SqlCommand(selectSql1, cnn1);
com1.Parameters.AddWithValue("productIdFilter", productIdFilter);
OnTextChanged Event in Code Behind
protected void txtProductId_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["_connect"].ToString());
int ProductId = Convert.ToInt32(txtProductId.Text);
SqlCommand com = con.CreateCommand();
com.CommandText = "sp_ProductGetData";
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Mode", 1);
com.Parameters.AddWithValue("#ProductId", ProductId);
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
dr.Read();
txtProductCategory.Text = Convert.ToString(dr["ProductCategory"]);
txtProductName.Text = Convert.ToString(dr["ProductName"]);
txtPrice.Text = Convert.ToString(dr["Price"]);
}
else
{
ScriptManager.RegisterClientScriptBlock((Page)(HttpContext.Current.Handler), typeof(Page), "alert", "javascript:alert('" + Convert.ToString(("No Record Found with Prodcut Id: "+ProductId)) + "');", true);
return;
}
con.Close();
}
Stored Procedure
CREATE PROCEDURE sp_ProductGetData
(
#Mode INT=NULL,
#ProductId INT=NULL
)
AS
BEGIN
IF(#Mode=1)
BEGIN
SELECT ProductCategory,ProductName,Price FROM Product
WHERE ProductId=#ProductId
END
END
Can somebody help understand this code?
protected void Page_Load(object sender, EventArgs e)
{
Database database = new Database();
OleDbConnection conn = database.connectDatabase();
if (Request.Cookies["BesteldeArtikelen"] == null)
{
lbl_leeg.Text = "Er zijn nog geen bestelde artikelen";
}
else
{
HttpCookie best = Request.Cookies["BesteldeArtikelen"];
int aantal_bestel = best.Values.AllKeys.Length;
int[] bestelde = new int[aantal_bestel];
int index = 0;
foreach (string art_id in best.Values.AllKeys)
{
int aantalbesteld = int.Parse(aantalVoorArtikel(int.Parse(art_id)));
int artikel_id = int.Parse(art_id); // moet getalletje zijn
if (aantalbesteld != 0)
{
bestelde[index] = artikel_id;
}
index++;
}
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT artikel_id, naam, prijs, vegetarische FROM artikel WHERE artikel_id IN (" +
String.Join(", ", bestelde) + ")";
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
}
catch (Exception error)
{
errorMessage.Text = error.ToString();
}
finally
{
conn.Close();
}
}
}
And there is this part of code i dont really understand:
public string aantalVoorArtikel(object id)
{
int artikel_id = (int)id;
if (Request.Cookies["BesteldeArtikelen"] != null &&
Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()] != null)
{
return Request.Cookies["BesteldeArtikelen"][artikel_id.ToString()];
}
else
{
return "0";
}
}
It extracts values from a cookie and builds an int array. (Displays a message if the cookie value is null) The int array is then used as the value for the SQL IN operator when querying the database. The result set is then bound to the GridView.
I want to make a library system in C#. In this system when a book is issued it should automatically reduce the book quantity in database. When book quantity == 0 there should be a message box showing "not available".
This is my code:
private void btnIssue_Click(object sender, EventArgs e)
{
if (cmbResID.Text != "" && cmbMemID.Text != "" && cmbBookID.Text != "" && txtBkTitle.Text != "" && txtCategory.Text != "" && txtAuthor.Text != "" && txtIssueDate.Text != "" && txtActDate.Text != "")
{
SqlCommand Quantity = new SqlCommand("Select * from tblBookDetails where Book_ID = '" + cmbBookID.Text +"'");
DataSet ds = Library.Select(Quantity);
if (ds.Tables[0].Rows.Count > 0)
{
textBox1.Text = ds.Tables[0].Rows[0].ItemArray.GetValue(5).ToString();
int b = Convert.ToInt32(textBox1.Text);
if (b > 0)
{
//a = a - 1;
//int b = Convert.ToInt32(a);
//label15.Text = a.ToString();
SqlCommand update=new SqlCommand("UPDATE tblBookDetails SET Quantity=Quantity-1 WHERE Book_ID='"+ cmbBookID +"'");
Library.ExecuteInsert(update);
SqlCommand save = new SqlCommand("insert into tblBookIssue values(#ResID,#Member_ID,#Book_ID,#Issue_Date,#Act_Ret_Date)");
save.Parameters.AddWithValue("#ResID", cmbResID.Text);
save.Parameters.AddWithValue("#Member_ID", cmbMemID.Text);
save.Parameters.AddWithValue("#Book_ID", cmbBookID.Text);
save.Parameters.AddWithValue("#Issue_Date", txtIssueDate.Text);
save.Parameters.AddWithValue("#Act_Ret_Date", txtActDate.Text);
Library.Insert(save);
MessageBox.Show("Book Issued", "Book Issue", MessageBoxButtons.OK, MessageBoxIcon.Information);
clear();
}
else
{
MessageBox.Show("this book is not available");
}
}
}
else
{
MessageBox.Show("FILL COLUMS");
}
}
Executing SQL based off of text boxes is very unsafe and Prone to SQL injection attacks. Also, to follow Object Oriented program and make much cleaner code it would be advisable to make a Book object, I completed some code below which shows an example including the book incrementer. It would be better to make focused stored procs which execute gets for books and updates for book checkouts. You will have to turn your basic select into a stored proc, and write another proc which looks at the quantity and if quantity < 1 return 0 else return 1. Let me know if you need more info, this code should help you get rolling
using System;
using System.Data;
using System.Data.SqlClient;
namespace MockLibrary
{
internal class Book
{
#region Constructors
public Book()
{
}
public Book(string resId, string memberId, string bookId, DateTime issueDate, DateTime actRetDate)
{
this.ResId = resId;
this.MemberId = memberId;
this.BookId = bookId;
this.IssueDate = issueDate;
this.ActRetDate = actRetDate;
}
#endregion
#region Properties
private string _ResID;
private string _MemberID;
private string _BookId;
private DateTime _IssueDate;
private DateTime _ActRetDate;
public string ResId
{
get { return _ResID; }
set { _ResID = value; }
}
public string MemberId
{
get { return _MemberID; }
set { _MemberID = value; }
}
public string BookId
{
get { return _BookId; }
set { _BookId = value; }
}
public DateTime IssueDate
{
get { return _IssueDate; }
set { _IssueDate = value; }
}
public DateTime ActRetDate
{
get { return _ActRetDate; }
set { _ActRetDate = value; }
}
#endregion
public Book GetBookByID(string resId, string memberId)
{
try
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_GetBookById", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Book newBook = new Book(rdr["ResId"].ToString(),rdr["MemberId"].ToString(),rdr["BookId"].ToString(),DateTime.Now,DateTime.Now);
return newBook;
}
}
}
}
catch
{
throw new Exception("something went wrong");
}
return null;
}
public bool CheckoutBook(string resId, string memberId)
{
using (SqlConnection con = new SqlConnection("put your db con string here"))
{
using (SqlCommand cmd = new SqlCommand("sp_CheckoutBook", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#ResId", SqlDbType.VarChar).Value = resId;
cmd.Parameters.Add("#MemberId", SqlDbType.VarChar).Value = memberId;
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (rdr["checkoutsuccessful"].ToString() == "1")
{
return true;
}
}
}
}
return false;
}
}
}
when user returns a book:-
MySqlCommand cm1;
cm1 = new MySqlCommand("update addbook set bookquantity=bookquantity+1 where bookname='" + txt_bookname.Text + "'",con);
cm1.ExecuteNonQuery();
i am using C# and i need to develop a check system for a mysql user and password.
So far what ive come up with is this and the error i get is that it is the wrong syntax...
public bool VerifyUser(string username, string password)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character WHERE User='" + username + "'";
MySqlCommand verifyUser = new MySqlCommand(Query, this.sqlConn);
try
{
verifyUser.ExecuteNonQuery();
MySqlDataReader myReader = verifyUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not verify user. Error: " +
excp.Message, excp);
throw (myExcp);
}
if (returnValue == password)
{
return false;
}
else
{
return true;
}
}
ExecuteNonQuery is for DELETE, INSERT and UPDATE. Whenever you want data returned as rows from database, use ExecuteReader
Your query should check the username and password together, if they exist in one record then the row is returned else nothing is returned.
You still need more to learn about coding/database programming using .Net
public bool VerifyUser(string username, string password)
{
bool returnValue = false;
string Query = "SELECT 1 FROM Base_Character WHERE User='" + username + "' AND pass='"+password+"'";
try
{
MySqlCommand command = new MySqlCommand(Query, this.sqlConn);
MySqlDataReader myReader = command.ExecuteReader();
if(myReader.Read())
{
returnValue = true;
}
myReader.Close();
}
catch (Exception excp)
{
throw;
}
return returnValue;
}
You should probably not throw a custom exception since you are using boolean
if(VerifyUser("user123", "******"))
{
//Congratulations
}
else
{
//Unable to log you in
}
Thanks guys, but this calls for a custom encryption that mysql cant hold or process, my main error was ovrlooking the executenonquery(), so i had to make the code like this:
if (AuthorizeTools.Encrypt.Password(Database.getPassword) != Password) //Password is already encrypted
Then set the mysql function to:
public string getPassword(string username)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character where (User=" +
"'" + username + "') LIMIT 1";
MySqlCommand checkUser = new MySqlCommand(Query, this.sqlConn);
try
{
checkUser.ExecuteNonQuery();
MySqlDataReader myReader = checkUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not grab password: " +
excp.Message, excp);
throw (myExcp);
}
return (returnValue);
}