File manager - Edit - G:/PleskVhosts/indiaminerals.in/vgm.INFOFIXDEVELOPERS.COM/admin/purchase.aspx.cs
Back
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Configuration; using WebApp.LIBS; using System.IO; namespace VGM.admin { public partial class purchase : BasePageClass { string cs = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; SqlConnection con; SqlCommand cmd; SqlDataAdapter da; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { try { using (SqlConnection connection = new SqlConnection(cs)) { string query = "select distinct(Medicine_name) from medicine"; using (SqlCommand command = new SqlCommand(query, connection)) { connection.Open(); ddlMedicine.Items.Add(new ListItem("Select Medicine", "")); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { string medicineName = reader["Medicine_name"].ToString(); ListItem item = new ListItem(medicineName, medicineName); ddlMedicine.Items.Add(item); } } } } } catch (Exception ex) { // Log the exception details Console.WriteLine("Exception during Page_Load: " + ex.ToString()); // Display an error message to the user if needed Response.Write("<script>alert('An error occurred during page load: " + ex.Message + "')</script>"); } if (ViewState["MedicineData"] == null) { // Create a DataTable to store treatment data DataTable dt1 = new DataTable(); dt1.Columns.Add("Medicine_name", typeof(string)); dt1.Columns.Add("Quantity", typeof(int)); dt1.Columns.Add("Expiry_date", typeof(DateTime)); dt1.Columns.Add("Rate", typeof(int)); dt1.Columns.Add("Batch_no", typeof(string)); ViewState["MedicineData"] = dt1; } // Bind the GridView with the data stored in ViewState DataTable dt2 = ViewState["MedicineData"] as DataTable; Gridview1.DataSource = dt2; Gridview1.DataBind(); int generatedID = GenerateUniqueID(); id.Text = generatedID.ToString(); } } private int GenerateUniqueID() { using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["gav"].ConnectionString)) { connection.Open(); // Retrieve the highest existing Issue_id in the issue table string getMaxIssueIdQuery = "SELECT MAX(ID) FROM purchase"; using (SqlCommand getMaxIssueIdCommand = new SqlCommand(getMaxIssueIdQuery, connection)) { object maxIssueId = getMaxIssueIdCommand.ExecuteScalar(); if (maxIssueId != DBNull.Value) { return (int)maxIssueId + 1; } else { return 1; } } } } protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "DeleteRow") { int rowIndex = Convert.ToInt32(e.CommandArgument); DataTable dt = ViewState["MedicineData"] as DataTable; if (dt != null && dt.Rows.Count > rowIndex) { // Remove the row from the DataTable dt.Rows.RemoveAt(rowIndex); ViewState["MedicineData"] = dt; // Rebind the GridView to reflect the updated data Gridview1.DataSource = dt; Gridview1.DataBind(); } } } protected void submitBtn2_Click(object sender, EventArgs e) { try { DataTable dt1 = new DataTable(); if (ViewState["MedicineData"] != null) { dt1 = (DataTable)ViewState["MedicineData"]; } // Your database connection string string connectionString = ConfigurationManager.ConnectionStrings["gav"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); foreach (DataRow row in dt1.Rows) { string by; if (supplierRadio.Checked == true) { by = "Supplier"; } else { by = "Donor"; } string medicineName = row["Medicine_name"].ToString(); int quantity = Convert.ToInt32(row["Quantity"]); // Retrieve the medicine_id based on medicine_name int medicineId; string getMedicineIdQuery = "SELECT ID FROM medicine WHERE medicine_name = @MedicineName"; using (SqlCommand getMedicineIdCommand = new SqlCommand(getMedicineIdQuery, connection)) { getMedicineIdCommand.Parameters.AddWithValue("@MedicineName", medicineName); medicineId = Convert.ToInt32(getMedicineIdCommand.ExecuteScalar()); } // Check if the medicine already exists in the stock table string checkQuery = "SELECT COUNT(*) FROM stock WHERE Medicine_id = @MedicineId"; using (SqlCommand checkCommand = new SqlCommand(checkQuery, connection)) { checkCommand.Parameters.AddWithValue("@MedicineId", medicineId); int existingCount = Convert.ToInt32(checkCommand.ExecuteScalar()); if (existingCount > 0) { // If the medicine exists, update the quantity string updateQuery = "UPDATE stock SET Purchase_stock = Purchase_stock + @Purchase_stock WHERE Medicine_id = @MedicineId"; using (SqlCommand updateCommand = new SqlCommand(updateQuery, connection)) { updateCommand.Parameters.AddWithValue("@MedicineId", medicineId); updateCommand.Parameters.AddWithValue("@Purchase_stock", quantity); updateCommand.ExecuteNonQuery(); } } else { // If the medicine doesn't exist, insert a new record into the stock table string insertStockQuery = "INSERT INTO stock(Medicine_id, Purchase_stock) VALUES (@MedicineId, @Purchase_stock)"; using (SqlCommand insertStockCommand = new SqlCommand(insertStockQuery, connection)) { insertStockCommand.Parameters.AddWithValue("@MedicineId", medicineId); insertStockCommand.Parameters.AddWithValue("@Purchase_stock", quantity); insertStockCommand.ExecuteNonQuery(); } } } // Insert data into the purchase table string purchaseQuery = "INSERT INTO purchase(ID,Purchase_date, Medicine_by, Supplier_Donor_name, Medicine_id, Quantity, Expiry_date, Rate, Batch_no) VALUES (@ID,@Purchase_date, @Medicine_by, @Supplier_Donor_name, @MedicineId, @Quantity, @Expiry_date, @Rate, @Batch_no)"; using (SqlCommand command = new SqlCommand(purchaseQuery, connection)) { command.Parameters.AddWithValue("@ID", id.Text); command.Parameters.AddWithValue("@Purchase_date", Convert.ToDateTime(purchaseDate.Text).ToString("dd-MMM-yyyy")); command.Parameters.AddWithValue("@Medicine_by", by); command.Parameters.AddWithValue("@Supplier_Donor_name", name.Text); command.Parameters.AddWithValue("@MedicineId", medicineId); command.Parameters.AddWithValue("@Quantity", quantity); command.Parameters.AddWithValue("@Expiry_date", row["Expiry_date"]); command.Parameters.AddWithValue("@Rate", row["Rate"]); command.Parameters.AddWithValue("@Batch_no", row["Batch_no"]); // Execute the SQL command to insert data into the purchase table command.ExecuteNonQuery(); } } } Response.Write("<script>if(confirm('Data inserted successfully.')){ window.location = 'Purchase_list.aspx'; }</script>"); Gridview1.DataSource = null; Gridview1.DataBind(); SaveToCSV(); } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } private void SaveToCSV() { try { string dateTime = DateTime.Now.ToString("yyyy-MM-dd"); string time = DateTime.Now.ToString("HH:mm:ss"); string tittle = "Medicine Purchase Master"; // Get additional details (you may customize this part) string details; if (supplierRadio.Checked == true) { details = "Medicine Purchase From Supplier"; } else { details = "Medicine Donated By Donor"; } // Combine date, time, and details in CSV format with comma delimiter string contentToSave = $"\"{dateTime}\",\"{time}\",\"{tittle}\",\"{details}\""; // Specify the path to the CSV file (including the file name) string filePath = Server.MapPath("~/data/LogData.csv"); // Check if the directory exists, if not, create it string directoryPath = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } // Check if the file exists, if not, create and add headers if (!File.Exists(filePath)) { File.WriteAllText(filePath, "Date,Time,Tittle,Details" + Environment.NewLine); } // Save the content to the file File.AppendAllText(filePath, contentToSave + Environment.NewLine); } catch (Exception ex) { Response.Write("<script>alert('An error occurred while saving to CSV: " + ex.Message + "')</script>"); } } protected void addButton_Click1(object sender, EventArgs e) { try { DataTable dt = ViewState["MedicineData"] as DataTable; // Check if the selected "Medicine_name" already exists in the GridView string selectedMedicineName = ddlMedicine.Value; bool isMedicineNameExists = false; foreach (DataRow row in dt.Rows) { if (row["Medicine_name"].ToString() == selectedMedicineName) { // Add the quantity to the existing row int existingQuantity = Convert.ToInt32(row["Quantity"]); int newQuantity = int.Parse(quantity.Text); row["Quantity"] = existingQuantity + newQuantity; isMedicineNameExists = true; break; // Exit the loop since we found a match } } if (!isMedicineNameExists) { // If the selected "Medicine_name" doesn't exist, create a new row DataRow newRow = dt.NewRow(); newRow["Medicine_name"] = selectedMedicineName; newRow["Quantity"] = int.Parse(quantity.Text); newRow["Expiry_date"] = DateTime.Parse(expiryDate.Text); newRow["Rate"] = int.Parse(rate.Text); newRow["Batch_no"] = batchNo.Text; dt.Rows.Add(newRow); } ViewState["MedicineData"] = dt; // Rebind the GridView Gridview1.DataSource = dt; Gridview1.DataBind(); } catch (Exception ex) { Response.Write("<script>alert('An error occurred: " + ex.Message + "')</script>"); } } } }
| ver. 1.4 |
Github
|
.
| PHP 7.3.33 | Generation time: 0.09 |
proxy
|
phpinfo
|
Settings