how to auto generate id from date in asp.net c# - c#

i want to auto generate Id from date entered by user.
Example: date is 12/05/2017 than id must 170001 or 5/10/2014 than id must 140001
private void autogeneratedocno()
{
con.Open();
string check="select count(Doc_no) from
complaint";
SqlCommand cmd2 = new SqlCommand(check,con);
int a =Convert.ToInt32(cmd2.ExecuteScalar());
string date = txtdate.Text.ToString();
string year = date.Substring(8, 2);
//string[] arrDate = date.Split('/');
//string day = arrDate[0].ToString();
//string month = arrDate[1].ToString();
//string year = arrDate[2].ToString();
//string y = year.Substring(2, 2);
if (a == 0)
{
txtdocno.Text = string.Concat( year.ToString()
+ "00000");
}
else
{
string count = "select ISNULL(MAX(Doc_no),0)+1
from complaint";
SqlCommand cmd = new SqlCommand(count, con);
int doc_no =
Convert.ToInt32(cmd.ExecuteScalar());
txtdocno.Text = doc_no.ToString();
}
con.Close();
}
by using above code. i am able to generate id for year 2017 but when i change the year the first two digits are not changing.
please suggest me changes to autogenerate ID

lbldate.Text = Convert.ToDateTime(DateTime.Now.AddYears(-3)).ToString("dd/MM/yyyy");
string Year = lbldate.Text.Substring(8, 2);
lblYear.Text = Year;

This may help you solve the problem you are having, but you may find you will have other issues down the line.
I opted to converting the string input to a DateTime as you cannot guarantee what a user will input. What if they enter the date like 2017-01-01.
For instance this will fail for 2009 as the int.parse will remove the leading zeros.
string date = "01/01/2017"; //example date
DateTime d = DateTime.Parse(date); //convert string into datetime
var i = int.Parse(d.ToString("yy00000")); //format and convert to int
int docno = i + count
You should maybe look at generating a number from the database or possibly using a GUID

private void autogeneratedocno()
{
string str1 = txtdate.Text;
string[] s1 = str1.Split('/');
str1 = s1[1].ToString() + "/" + s1[0].ToString() +
"/" + s1[2].ToString();
string yy = s1[2].ToString();
string mm = s1[1].ToString();
string dd = s1[0].ToString();
int y = Convert.ToInt32(yy);
int m = Convert.ToInt32(mm);
string z = yy.Substring(2,2);
string sqlno =" selectisnull(max(substring
(doc_no,3,5)),0)+1 from complaint where
substring(doc_no,1,2) = '"+z+"'";
con.Open();
SqlCommand cmd = new SqlCommand(sqlno, con);
string getno =
Convert.ToString(cmd.ExecuteScalar());
con.Close();
string Inquiry_code = yy.Substring(2, 2) +
getno.ToString().PadLeft(5, '0');
txtdocno.Text = Inquiry_code;
}
finally got the answer.
Please Suggest if you have other Ideas to do this.

Related

retrieved date data from mysql is not the exact data shown on a label in c#

I want to display the contents of a certain column on a label, but when i get to this certain column which is in a date datatype.. it adds a "12:00:00 AM" and i want to remove it so that only the correct date and time pair will be joined together in a string. i am not allowed to alter the database table..
how can i eliminate that "12:00:00 AM" part of the string.. is it possible?
i am sure that its a date data type, but it gives one that looks like a datetime datatype.
well i'm clearly a newbie, and any suggestion or help is highly appreciated. Thank you so much.
the part of the database
when i retrieve a certain data in the db table, the label is not showing the exact same thing thats on the database
private void dbdateBtn_Click(object sender, EventArgs e)
{
//db read
string constring = "SERVER = localhost; user id = root; password =; database = mpdb";
string Query = "select * from mpdb.cicotbl where cico_no='" + this.textBox1.Text + "';";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
while (myReader.Read())
{
string firstdate = myReader.GetString("CINd");
string seconddate = myReader.GetString("COUTd");
string time1 = myReader.GetString("CINt");
string time2 = myReader.GetString("COUTt");
dbdate1.Text = firstdate + " " + time1;
dbdate2.Text = seconddate + " " + time2;
}
conDataBase.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Hand);
}
}
I believe it's because the date is stored in the database as a date-time variable, a short fix is to use:
DateTime firstdate = DateTime.Parse(myReader.GetString("CINd"));
DateTime seconddate = DateTime.Parse(myReader.GetString("COUTd"));
string firstdatestring = firstdate.ToLongDateString();
string seconddatestring = seconddate.ToLongDateString();
string time1 = myReader.GetString("CINt");
string time2 = myReader.GetString("COUTt");
dbdate1.Text = firstdatestring + " " + time1;
dbdate2.Text = seconddatestring + " " + time2;

Insert Multiple Textbox and Label value in single Query using For loop

for (int i = 1; i <= daysCount; i++)
{
conn.Open();
string sQuery = "INSERT INTO TripSheet VALUES('" + lblDate1.Text + "','" + txtFuel1.Text+ "','" + txtRate1.Text + "')";
SqlCommand cmd = new SqlCommand(sQuery, conn);
cmd.ExecuteNonQuery();
conn.Close();
}
Here I am taking month count and I have to insert the Month of data using loop.
lblDate1.Text, txtFuel1.Text & txtRate.Text
This value I want to pass Like
lblDate[i].Text, txtFuel[i].Text & txtRate[i].Text (Is it possible?)
Normally I would expect these values to be in some sort of a collection of objects where they have been scrubbed from the user interface. For example as a List or and Array of a given type. I would also typically see this inserting the SQL data by type of that data for example a datetime for the date, VARCHAR(30) for the name and so forth. Now given I do not have visibility to that, I use the less desired perhaps AddWithValue here. I typed this really fast so might be errors. Put this in a proper set of classes and files.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Data.SqlClient;
namespace Rates
{
public class FuelRateThing
{
public DateTime RateDate
{
get;
set;
}
public decimal FuelRate
{
get;
set;
}
public string FuelName
{
get;
set;
}
public FuelRateThing()
{
}
public FuelRateThing(DateTime date, decimal rate, string name)
{
RateDate = date;
FuelRate = rate;
FuelName = name;
}
}
public class Ratethings
{
public void dostuff()
{
CultureInfo provider = CultureInfo.InvariantCulture;
//Create a class to manage these objects perhaps, here is a simple list example.
// populate your list - normally parse and validation of UI values:
List<FuelRateThing> monthRatesList = new List<FuelRateThing>()
{new FuelRateThing{RateDate = DateTime.ParseExact("20180101", "yyyyMMdd", provider), FuelRate = 3.45m, FuelName = "kerosene"}, new FuelRateThing{RateDate = DateTime.ParseExact("20180102", "yyyyMMdd", provider), FuelRate = 3.49m, FuelName = "kerosene"}, new FuelRateThing{RateDate = DateTime.ParseExact("20180103", "yyyyMMdd", provider), FuelRate = 3.48m, FuelName = "kerosene"}, new FuelRateThing{RateDate = DateTime.ParseExact("20180104", "yyyyMMdd", provider), FuelRate = 3.65m, FuelName = "kerosene"}, new FuelRateThing{RateDate = DateTime.ParseExact("20180105", "yyyyMMdd", provider), FuelRate = 3.60m, FuelName = "kerosene"}, };
// add a couple more rows
monthRatesList.Add(new FuelRateThing(DateTime.ParseExact("20180106", "yyyyMMdd", provider), 3.64m, "kerosene"));
var newrate = new FuelRateThing{RateDate = DateTime.ParseExact("20180107", "yyyyMMdd", provider), FuelRate = 3.47m, FuelName = "kerosene"};
monthRatesList.Add(newrate);
}
//Now use the data access code to insert those: (probably in a method that accepts a list of `FuelRateThings`:
public class DataStore
{
public void SaveRateThings(List<FuelRateThing> rateList)
{
var _connectionSB = new SqlConnectionStringBuilder();
// do connections string stuff here
var _connectionString = _connectionSB.ToString();
using (SqlConnection connection = new SqlConnection(_connectionString))
{
String query = #"
INSERT INTO TripSheet (DateColumnName,FuelColumnName,RateColumnName)
VALUES (#DateColumnName,#FuelColumnName,#RateColumnName)";
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
foreach (FuelRateThing rate in rateList)
{
command.Parameters.AddWithValue("#DateColumnName", rate.RateDate);
command.Parameters.AddWithValue("#FuelColumnName", rate.FuelName);
command.Parameters.AddWithValue("#RateColumnName", rate.FuelRate);
int result = command.ExecuteNonQuery();
}
}
}
}
}
}
}
INSERT INTO tab (id) VALUES (1), (2), (3);
or
INSERT INTO tab(a,b,c)
SELECT * FROM
(
VALUES
(1,2,3),
(10,20,30),
(100,200,300)
) s(a,b,c);
c#
string temp="";
for (int i = 1; i <= daysCount; i++)
{
if(i!=1)
temp+=",";
temp+="('" + lblDate1.Text + "','" + txtFuel1.Text+ "','" + txtRate1.Text + "')";
}
conn.Open();
string sQuery = "INSERT INTO TripSheet VALUES "+temp;
SqlCommand cmd = new SqlCommand(sQuery, conn);
cmd.ExecuteNonQuery();
conn.Close();

Using UPDATE in my loop?

string inserttest = "UPDATE Warranty([LenovoBaseWarrantyStartDate], [LenovoBaseWarrantyEndDate], [LenovoBaseWarrantyStatus])"
+ "VALUES (#LenovoBaseWarrantyStartDate, #LenovoBaseWarrantyEndDate, #LenovoBaseWarrantyStatus)";
OleDbCommand cmd = new OleDbCommand(inserttest, conn1);
OleDbCommand accessCommand = conn1.CreateCommand();
accessCommand.CommandText = ("SELECT SerialNumber from Warranty");
OleDbDataReader accessReader = accessCommand.ExecuteReader();
int count = accessReader.FieldCount;
List<StoreClass> storeList = new List<StoreClass>();
while (accessReader.Read())
{
for (int i = 0; i < count; i++)
{
string result = accessReader.GetValue(i).ToString();
webBrowser1.Document.GetElementById("serialCode").Focus();
webBrowser1.Document.GetElementById("serialCode").InnerText = result;
webBrowser1.Document.GetElementById("warrantySubmit").InvokeMember("Click");
Thread.Sleep(500);
MessageBox.Show("Serial Number:" + " " + result);
foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
if (el.GetAttribute("className") == "fluid-row Borderfluid")
{
string record = el.InnerText;
var result1 = parseString(record);
string StartDate = string.Join("", result1.ConvertAll(r => string.Format("{0}", r)).ToArray());
DateTime strStartDate = DateTime.ParseExact(StartDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
string EndDate = string.Join("", result1.ConvertAll(r => string.Format("{1}", r)).ToArray());
DateTime strEndDate = DateTime.ParseExact(EndDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
string Status = string.Join("", result1.ConvertAll(r => string.Format("{2}", r)).ToArray());
bool strStatus = "Active" == "1" && "Expired" == "0";
storeList.Add(new StoreClass(strStartDate, strEndDate, strStatus));
cmd.Parameters.Add("#LenovoBaseWarrantyStartDate", OleDbType.Date).Value = storeList[0].startDate;
cmd.Parameters.Add("#LenovoBaseWarrantyEndDate", OleDbType.Date).Value = storeList[0].endDate;
cmd.Parameters.Add("#LenovoBaseWarrantyStatus", OleDbType.Boolean).Value = storeList[0].status;
cmd.Parameters.Add("#LenovoWarrantyUpgradeStartDate", OleDbType.Date).Value = storeList[1].startDate;
cmd.Parameters.Add("#LenovoWarrantyUpgradeEndDate", OleDbType.Date).Value = storeList[1].endDate;
cmd.Parameters.Add("#LenovoWarrantyUpgradeStatus", OleDbType.Boolean).Value = storeList[1].status;
cmd.Parameters.Add("#LenovoPrioritySupportStartDate", OleDbType.Date).Value = storeList[2].startDate;
cmd.Parameters.Add("#LenovoPrioritySupportEndDate", OleDbType.Date).Value = storeList[2].endDate;
cmd.Parameters.Add("#LenovoPrioritySupportStatus", OleDbType.Boolean).Value = storeList[2].status;
//...
}
//...
}
//...
}
Sorry for the wall of code but its to give you an idea of what I am trying to figure out. I have this loop to retrieve data and store it into a database table. I am trying to edit my inserttest statement at the top so I can update the columns in the specific Serial Number it is currently looping through.
Is there a way to do this? I can't do Update Warranty ... Where SerialNumber = result cause it only exists in the loop (unless I can and I just dont know how).
You pass it in as another parameter, and add the where clause
WHERE SerialNumber = #result

How to insert Data into sql server database

I'm trying to insert data into my SQL Server 2014 database, but I get an error
Incorrect syntax near ')'.
My table matches the types of data I put in, for example, I'm put an int into a int.
Here is my code:
string ip = Request.UserHostAddress;
string name = "Jesus said: Love your Enemies (V.S.)";
int blueq = Convert.ToInt32(TextBox1.Text);
int redq = Convert.ToInt32(TextBox2.Text);
int whiteq = Convert.ToInt32(TextBox3.Text);
int blackq = Convert.ToInt32(TextBox4.Text);
int whiteqr = Convert.ToInt32(TextBox9.Text);
int redqr = Convert.ToInt32(TextBox10.Text);
int sn = 600;
int price = total_jslye;
string size;
if (RadioButton1.Checked == false)
{
size = "11x35";
}
else
size = "18x50";
try
{
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["SQLCS"].ConnectionString;
var cmd = "INSERT INTO cartsigns (#SignNumber, #redquantity, #bluequantity, #whitequantity, #blackquantity, #whitereflectivequantity, #redreflectivequantity, #size, #SignName, #ipaddress, #price)";
using (SqlConnection com = new SqlConnection(conn))
{
using (SqlCommand cmds = new SqlCommand(cmd, com))
{
cmds.Parameters.AddWithValue("#SignNumber", sn);
cmds.Parameters.AddWithValue("#redquantity", redq);
cmds.Parameters.AddWithValue("#bluequantity", blueq);
cmds.Parameters.AddWithValue("#whitequantity", whiteq);
cmds.Parameters.AddWithValue("#blackquantity", blackq);
cmds.Parameters.AddWithValue("#whitereflectivequantity", whiteqr);
cmds.Parameters.AddWithValue("#redreflectivequantity", redqr);
cmds.Parameters.AddWithValue("#size", size);
cmds.Parameters.AddWithValue("#SignName", name);
cmds.Parameters.AddWithValue("#ipaddress", ip);
cmds.Parameters.AddWithValue("#price", price);
com.Open();
cmds.ExecuteNonQuery();
}
}
}
So please help, thanks
Your insert syntax is not correct. you have not given column names also keyword "Values" is missing in your query
Your parameter names can not have brackets or spaces in them in SQL Server. So rename them all to #SignNumber, #redquantity, #bluequantity... etc.
Try this code. you will get your desired result. The issue that you were getting in your code is because parameters are not supposed to have any spaces or brackets or any characters that makes the parameter names not well formed. A parameter name must begin with "#" character, and should follow the rules for object identifiers. Check the link for further details.
string ip = Request.UserHostAddress;
string name = "first sign";
int blueq = Convert.ToInt32(TextBox1.Text);
int redq = Convert.ToInt32(TextBox2.Text);
int whiteq = Convert.ToInt32(TextBox3.Text);
int blackq = Convert.ToInt32(TextBox4.Text);
int whiteqr = Convert.ToInt32(TextBox9.Text);
int redqr = Convert.ToInt32(TextBox10.Text);
int sn = 600;
int price = total_jslye;
string size;
if (RadioButton1.Checked == false)
{
size = "11x35";
}
else
size = "18x50";
try
{
string conn = System.Configuration.ConfigurationManager.ConnectionStrings["SQLCS"].ConnectionString;
var cmd = "INSERT INTO cartsigns ([Sign Number],[red quantity],[blue quantity],[white quantity],[black quantity],[white reflective quantity],[red reflective quantity],[size],[Sign Name],[ipaddress],[price]) values (#[Sign_Number],#[red_quantity],#[blue_quantity], #[white_quantity],#[black_quantity],#[white_reflective_quantity],#[red_reflective_quantity],#[size],#[Sign_Name],#[ipaddress],#[price])";
using (SqlConnection com = new SqlConnection(conn))
{
using (SqlCommand cmds = new SqlCommand(cmd, com))
{
cmds.Parameters.AddWithValue("#[Sign_Number]", sn);
cmds.Parameters.AddWithValue("#[red_quantity]", redq);
cmds.Parameters.AddWithValue("#[blue_quantity]", blueq);
cmds.Parameters.AddWithValue("#[white_quantity]", whiteq);
cmds.Parameters.AddWithValue("#[black_quantity]", blackq);
cmds.Parameters.AddWithValue("#[white_reflective_quantity]", whiteqr);
cmds.Parameters.AddWithValue("#[red_reflective_quantity]", redqr);
cmds.Parameters.AddWithValue("#[size]", size);
cmds.Parameters.AddWithValue("#[Sign_Name]", name);
cmds.Parameters.AddWithValue("#[ipaddress]", ip);
cmds.Parameters.AddWithValue("#[price]", price);
com.Open();
cmds.ExecuteNonQuery();
}
}
}
catch
{
throw;
}

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;
}

Categories

Resources