How to display only date in Label in C# - c#

with a combo selected index changed event I am taking data from table in my labels all going well except the date. Problem: Label is showing date with 12:00 and I need only date (dd/MMM/yyyy) not with time 12:00. This date is perfect in column of table and also in gridview. Only the label shows it wrongly in the Label (AcPtRgDateLbl.Text).
here is the code:
private void AcPtPtrDd_SelectedIndexChanged(object sender, EventArgs e)
{
cmd = new SqlCommand("SELECT * FROM Patients where pt_ptr='" + AcPtPtrDd.Text.ToString() + "'", con);
con.Open();
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string idn = (string)dr["pt_name"].ToString();
string idn1 = (string)dr["pt_date"].ToString();//Problem is here Please help to solve it.
string idn4 = (string)dr["pt_aid"].ToString();
string idn9 = (string)dr["pt_phone"].ToString();
AcPtNameLbl.Text = idn;
AcPtRgDateLbl.Text = idn1;
AcPtAidLbl.Text = idn4;
AcPtPhonLbl.Text = idn9;
if (AcPtAidLbl.Text == "-")
{
AcPtAidTxt.Enabled = false;
}
else
{
AcPtAidTxt.Enabled = true;
}
}
con.Close();
}
Tabel from SQL:
ALTER procedure [dbo].[pa_getPtAccountsDataLike]
#data nvarchar(50)
as
select
p.pta_id as 'ID',
p.pta_ptr as 'PtR',
p.pta_date as 'Date',
p.pta_fee as 'Fee',
p.pta_dis as 'Discount',
p.pta_aid as 'Aid',
p.pta_rcv as 'Receive',
p.pta_bal as 'Balance'
from PtAccounts p
where
p.pta_ptr like '%'+#data+'%'
or
p.pta_date like '%'+#data+'%'
order by p.pta_ptr desc

Try read as DateTime and then represent it as a string
string idn1 = Convert.ToDateTime(dr["pt_date"]).ToString("dd/MMM/yyyy");
More code (let's brush up your solution):
//DONE: required fields only; parametrized query
string sql =
#"SELECT pt_name,
pt_date,
pt_aid,
pt_phone
FROM Patients
WHERE pt_ptr = #pt_ptr";
//DONE: wrap IDisposable in using
using (var cmd = new SqlCommand(sql, con)) {
//TODO: cmd.Parameters.Add("#pt_ptr", AcPtPtrDd.Text, Rdbms_Type_Here);
// (explicit add) is a better implementation
cmd.Parameters.AddWithValue("#pt_ptr", AcPtPtrDd.Text);
using (var dr = cmd.ExecuteReader()) {
//DONE: we read at most one record only; no need in while
if (dr.Read()) {
AcPtNameLbl.Text = Convert.ToString(dr["pt_name"]);
AcPtRgDateLbl.Text = Convert.ToDateTime(dr["pt_date"]).ToString("dd/MMM/yyyy");
AcPtAidLbl.Text = Convert.ToString(dr["pt_aid"]);
AcPtPhonLbl.Text = Convert.ToString(dr["pt_phone"]);
}
else {
//DONE: what if we have an empty cursor?
AcPtNameLbl.Text = "";
AcPtRgDateLbl.Text = "";
AcPtAidLbl.Text = "-";
AcPtPhonLbl.Text = "";
}
AcPtAidTxt.Enabled = AcPtAidLbl.Text != "-";
}
}

Please try this
string idn1 = dr["pt_date"].ToString("dd/MMM/yyyy");

Related

how to create an id to be shown in the text box based on selected dropdownlist

i would like to create an id generator based on their department selected from the dropdownlist. lets say my ddl has 3 departments (A,B,C) and when generating an id it will be A20181001 and then A20181002 upon submission but when i pick B from the ddl after sending A20181001 to the database, it will be B20181001.
so far i have created the code for the increment for the id without the departments. here is the code i did so far. (I used the date for today so the 20181001 is just an example):
void getMRF_No()
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
int mrf = 0;
int i;
string a;
//string x = Request.QueryString["BUnit"];
string mrfNo = "";
database db = new database();
string conn = dbe.BU();
SqlConnection connUser = new SqlConnection(conn);
SqlCommand cmd = connUser.CreateCommand();
SqlDataReader sdr = null;
string query = "SELECT TOP 1 MRF_NO FROM incMRF ORDER BY MRF_NO DESC";
connUser.Open();
cmd.CommandText = query;
sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr.GetInt32(0).ToString();
}
if (mrfNo == "")
{
mrfNo = Convert.ToString(year) + "" + 00;
}
mrf += 0;
i = Convert.ToInt32(mrfNo) + 1;
a = i.ToString();
txtMRFNo.Text = a;
connUser.Close();
}
any help to improve this code will be helpful. thank you :)
EDIT:
here is the dropdown list code:
void SelectBU()
{
string database = dbe.BU ();
using (SqlConnection con = new SqlConnection(database))
{
con.Open();
string query = "select BUnit from BusinessUnit";
using (SqlDataAdapter sda = new SqlDataAdapter(query, con))
{
DataSet ds = new DataSet();
sda.Fill(ds, "BUnit");
ddlBu.DataSource = ds;
ddlBu.DataTextField = "BUnit";
ddlBu.DataValueField = "BUnit";
ddlBu.DataBind();
selectOption(ddlBu, "Select Dept");
}
con.Close();
}
}
EDIT2: I will state what im searching for here incase some doesnt know or understand. What i want is upon selecting a department from a dropdownlist, for example i picked A. the textbox show show A2018102201. if i select B it should show B2018102201 and if its C then c2018102201. and it will change its number once i submit it to a database and a new form loads. So if A2018102201 is already in the database, then the text shown in the text box will be A2018102202. BUT if i select B then the textbox will show B2018102201 since it does not exist in the database yet.
First you should get max ID, then increase the numeric part of your Id, and If this is a multi-user application, you have to lock your table, because it might create many ID duplication, Therefore I'm not recommend to create ID like this on c#, it is better to create a Sequence on SQL server. but I wrote this sample for you, just call it with proper value.
static string getMRF_No(string prefixCharFromDropDownList)
{
string year = DateTime.Now.Date.ToString("yyyyMMdd");
string mrfNo = "";
SqlConnection connUser = new SqlConnection("Server=130.185.76.162;Database=StackOverflow;UID=sa;PWD=$1#mssqlICW;connect timeout=10000");
SqlCommand cmd = new SqlCommand(
$"SELECT MAX(MRF_NO) as MaxID FROM incMRF where MRF_NO like '{prefixCharFromDropDownList}%'"
,connUser
);
connUser.Open();
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
mrfNo = sdr["MaxID"].ToString();
}
if (mrfNo == "")
{
mrfNo = prefixCharFromDropDownList + year + "000";
}
else
{
mrfNo = prefixCharFromDropDownList + (long.Parse(mrfNo.Substring(1)) + 1).ToString().PadLeft(2);
}
sdr.Close();
cmd = new SqlCommand($"INSERT INTO incMRF (MRF_NO) values ('{mrfNo}')",connUser);
cmd.ExecuteNonQuery();
connUser.Close();
//txtMRFNo.Text = prefixCharFromDropDownList + i.ToString();
return mrfNo;
}
I call this method on a console application as test.
static void Main(string[] args)
{
// send dropdown (selected char) as prefix to method
var newAId = getMRF_No("A");
var newAnotherAId = getMRF_No("A");
var newBId = getMRF_No("B");
var newAnotherAId2 = getMRF_No("A");
Console.ReadKey();
}

Find a cell of a row in a gridview and do something on OnRowDataBound

I want to only set a single cell in a GridView row to Grey if the reader HasRows, on the OnRowDataBound event.
The code snippet changes the entire column color rather than a single cell.
For example: In the image I want only the cell next to "Jan" to be grey.
protected void setcolor(object sender, GridViewRowEventArgs e )
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (txtShopBranch.Text == "Area1")
{
int index = e.Row.RowIndex;
string checkdayone = "SELECT one FROM tblregulardays WHERE months = 'Jan' AND shopbranch = 'Area1' AND one = '1'";
NpgsqlCommand findDayOne = new NpgsqlCommand (checkdayone, con);
con.Open();
NpgsqlDataReader reader = findDayOne.ExecuteReader();
if(reader.HasRows)
{
e.Row.Cells[32].BackColor = System.Drawing.Color.Gray;
}
else
{
e.Row.Cells[32].BackColor = System.Drawing.Color.White;
}
con.Close();
}
}
}
You use the same static sql query for every row:
string checkdayone = #"SELECT one FROM tblregulardays
WHERE months = 'Jan'
AND shopbranch = 'Area1'
AND one = '1'";
so of course will always yield the same result. You have to use a parameterized query. Maybe:
string month = e.Row.Cells[31].Text.Trim();
string checkdayone = #"SELECT one FROM tblregulardays
WHERE months = #Month
AND shopbranch = 'Area1'
AND one = '1'";
NpgsqlCommand findDayOne = new NpgsqlCommand (checkdayone, con);
findDayOne.Parameters.AddWithValue("#Month", month);

Reset Autonumber in C# based on year and date using oracle database

i have auto generate number create automatically in C#. this sample like this PPP-150500001 , PPP-150500002 => PPP- is a string never change, 15 is a year, 05 is a date, and 00001 is auto generate number.
How Can i reset auto number after get a new year like PPP-160100001 .
this is my method:
public void NomerUrut()
{
long hitung;
string urut;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = #"SELECT NOPERMOHONAN FROM PERMOHONAN WHERE NOPERMOHONAN IN (SELECT MAX(NOPERMOHONAN)
FROM PERMOHONAN) ORDER BY NOPERMOHONAN DESC";
cmd.Connection = koneksi_manual.con;
koneksi_manual.con.Open(); //open connection
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
hitung = Convert.ToInt64(dr[0].ToString().Substring(dr["NOPERMOHONAN"].ToString().Length - 5, 5)) + 1;
string joinstr = "00000" + hitung;
DateTime dt = DateTime.Now; // take years and date in autonumber
urut = "PPP-" + dt.ToString("yy") + dt.ToString("MM") + joinstr.Substring(joinstr.Length - 5, 5);
//it will show PPP-150500002, PPP-150500003, etc
//how can i reset this autonumber after get new years like PPP-160100001
}
else
{
urut = "PPP-150500001"; // first form load will display this default autonumber
}
dr.Close();
txtNoPermohonan.Text = urut; //display auto generate number in a textbox
koneksi_manual.con.Close(); //close connection
}
Solved.
i have update for this question and i can finish it using another query to solve my problem. i can reset it every years..
this my update code:
public static string GenerateKodeUrut()
{
string nomor = "";
string date = DateTime.Now.ToString("yyyy/MM/dd").Substring(2, 2);
DateTime dt = DateTime.Now;
OracleCommand cmd = new OracleCommand();
OracleDataReader dr;
cmd.CommandText = (#"SELECT NOPERMOHONAN from PERMOHONAN
where substr(NOPERMOHONAN, 5,2) ='" + date + "' ORDER BY cast(substr(NOPERMOHONAN, 9,5) as number) DESC");
cmd.Connection = koneksi_manual.con;
dr = cmd.ExecuteReader();
dr.Read();
if (dr.HasRows)
{
string nmrTerakhir = (dr["NOPERMOHONAN"]).ToString().Remove(0, 8);
nomor = "PPP-" + date + dt.ToString("MM") + (Convert.ToInt32(nmrTerakhir) + 1).ToString("0000#");
}
else
{
nomor = "PPP-" + date + dt.ToString("MM") + "00001";
}
return nomor;
}
you can make a flage in your db to check it && your date.
i hope that code give you my idea
bool flage = false;
int checkdate = Convert.ToInt16(dt.ToString("MM"));
if (checkdate == 12) {
flage = true;
}
if (flage == true && checkdate == 1) {
//Write Your Code Here
flage = false;
}

Row to not visible if null

I am using windows form to build an application using datagridview. Every data grid contains an empty row at the top and I suspect that it is the way that I am populating them but as I am coming to the end, I am reluctant to change any of my code as I am a beginner.
Is there a simple way to check if a row if empty, then set that to not visible?
The code that I am using:
private void displayInGrid_Customers(string sqlcmd)
{
customersDataGridView.Rows.Clear();
connect.Open();
command.Connection = connect;
command.CommandText = sqlcmd;
reader = command.ExecuteReader();
customersDataGridView.Rows.Add();
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
rowadd.Cells[1].Value = reader["Forename"].ToString();
rowadd.Cells[2].Value = reader["Surname"].ToString();
rowadd.Cells[3].Value = reader["Address"].ToString();
rowadd.Cells[4].Value = reader["Town"].ToString();
rowadd.Cells[5].Value = reader["Postcode"].ToString();
rowadd.Cells[6].Value = reader["Date_Of_Birth"].ToString();
rowadd.Cells[7].Value = reader["Phone_Number"].ToString();
rowadd.Cells[8].Value = reader["Email"].ToString();
rowadd.Cells[9].Value = reader["Current_Rental"].ToString();
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
reader.Close();
connect.Close();
}
private void button_view_all_customers_Click(object sender, EventArgs e)
{
command.CommandText = "SELECT CUSTOMERS.Customer_ID, CUSTOMERS.Forename, CUSTOMERS.Surname, CUSTOMERS.Address, "
+ "CUSTOMERS.Town, CUSTOMERS.Postcode, CUSTOMERS.Date_Of_Birth, CUSTOMERS.Phone_Number, CUSTOMERS.Email, CUSTOMERS.Current_Rental "
+ "from CUSTOMERS LEFT JOIN STOCK ON CUSTOMERS.Current_Rental = STOCK.Product_ID";
string cmd = command.CommandText;
displayInGrid_Customers(cmd);
}
You could use the IsNullOrWhiteSpace. But before that, you have to check your sql statement, why you have empty rows result.
while (reader.Read())
{
DataGridViewRow rowadd = (DataGridViewRow)customersDataGridView.Rows[0].Clone();
if (!string.IsNullOrWhiteSpace(reader["Customer_ID"].ToString()))
{
rowadd.Cells[0].Value = reader["Customer_ID"].ToString();
//Others Stuff
//...
this.customersDataGridView.AllowUserToAddRows = false;
customersDataGridView.Rows.Add(rowadd);
}
}

How do you calculate the total amount of each loop that's being read in a foreach loop?

I've got a DataGridView that has 2 columns - product name and the quantity of it. So I grab each row in a foreach loop and calculate the price of it. I managed to do that but I can't seems to figure out how to store ALL the calculated rows into a single variable and insert them into a database.
This is what I have so far:
string cMedication = string.Empty;
string cQuantity = string.Empty;
string cAppointment = string.Empty;
foreach (DataGridViewRow row in this.dataPrescription.Rows)
{
cMedication = row.Cells[0].Value.ToString();
cQuantity = row.Cells[1].Value.ToString();
cAppointment = txtAppointmentID.Text;
if (cAppointment == "NO APPOINTMENT HAS BEEN MADE")
{
MessageBox.Show("Please make an appointment first at the Nurse counter", "WARNING");
}
else
{
//this.savePrescription(cMedication, cQuantity, cAppointment);
string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
string strCalc = "SELECT medicationPrice FROM MEDICATION WHERE medicationName= ('" + cMedication + "')";
using (SqlConnection connection = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdCalc = new SqlCommand(strCalc, connection))
{
connection.Open();
SqlDataReader readPrice = cmdCalc.ExecuteReader();
if (readPrice.Read())
{
string getPrice = readPrice["medicationPrice"].ToString();
double doublePrice = Convert.ToDouble(getPrice);
double doubleQuantity = Convert.ToDouble(cQuantity);
double result = doublePrice * doubleQuantity;
string answer = result.ToString();
//insert TOTAL amount to database below
}
readPrice.Close();
connection.Close();
}
}
}
}
If you're doing this kind of thing a lot then I would use some kind of ORM like Entity Framework (or write your own). Then you would just load / create entites and save them.
If that's overkill for what you're doing then you could build up an insert statement and execute it, much like you've done to query the medication price. Only as I've mentioned in the comment, use SqlParameters instead of string concatenation to avoid possible sql injection attacks.
Something like this (untested).
var builder = new StringBuilder("INSERT INTO MedicationLine (MedicationName, Quantity, Price) VALUES ");
int i = 0;
var parameters = new List<SqlParameter>();
foreach (DataGridViewRow row in this.dataPrescription.Rows)
{
string cAppointment = txtAppointmentID.Text;
if (cAppointment == "NO APPOINTMENT HAS BEEN MADE")
{
MessageBox.Show("Please make an appointment first at the Nurse counter", "WARNING");
return;
}
string cMedication = row.Cells[0].Value.ToString();
string cQuantity = row.Cells[1].Value.ToString();
i++;
string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
string strCalc = "SELECT medicationPrice FROM MEDICATION WHERE medicationName = #medicationName";
using (SqlConnection connection = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdCalc = new SqlCommand(strCalc, connection))
{
command.Parameters.Add(new SqlParameter("medicationName", cMedication);
connection.Open();
SqlDataReader readPrice = cmdCalc.ExecuteReader();
if (readPrice.Read())
{
string getPrice = readPrice["medicationPrice"].ToString();
double doublePrice = Convert.ToDouble(getPrice);
double doubleQuantity = Convert.ToDouble(cQuantity);
builder.AppendLine();
builder.Append("(";
builder.Append("#Name");
builder.Append(i);
builder.Append("#Qty");
builder.Append(i);
builder.Append("#Price");
builder.Append(i);
builder.Append("),";
parameters.Add(new SqlParameter("Name" + i.ToString(), medicationName);
parameters.Add(new SqlParameter("Qty" + i.ToString(), doubleQuantity);
parameters.Add(new SqlParameter("Price" + i.ToString(), doublePrice);
}
readPrice.Close();
connection.Close();
}
}
}
The idea is to end up with something like:
INSERT INTO MedicationLine (MedicationName, Quantity, Price) VALUES
(#Name1, #Qty1, #Price1),
(#Name2, #Qty2, #Price2),
(#Name3, #Qty3, #Price3),
...
Then execute it. Don't forget to trim the trailing comma.
using (var connection = new SqlConnection(strConnectionString))
{
using (var command = new SqlCommand(builder.ToString().TrimEnd(','), connection))
{
command.Parameters.AddRange(parameters.ToArray());
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
}
**Disclaimer
Syntax may be wrong as done without an IDE!

Categories

Resources