I'm using Access 2000-2003 database for C#. I like to have my TypeID to have a unique id as CHHTP001, CHHTP002 and etc, and display the id in TextBox before inserting new value in the database.
public void generateRateID()
{
string id;
con.Open();
string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
cmd = new OleDbCommand(rate, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr[0].ToString();
id = id + 1;
txtRateID.Text = "CHHRT" + id.PadLeft(3, '0');
}
con.Close();
}
The display in TextBox is CHHTP001 at first, then CHHTPCHHTP0011. How can I make the CHHTPCHHTP0011 to CHHTP002 and so on?
Use Regex. This should works as you want:
id = dr[0].ToString();//CHHTP001 Or CHHTP111
id = Regex.Replace(id, "\\d+", m => (int.Parse(m.Value) + 1).ToString(new string('0', m.Value.Length)));
txtRateID.Text = id;//CHHTP002 Or CHHTP112
Here is some general guidelines.
You should create an int variable that records what should be the number. That way you can manage your id easily. When you want to increment your id, just increment the variable.
When you want to convert the id to a string, first call ToString and PadLeft. Next you just concatenate the string to "CHHTP"! Isn't that easy?
Try this:
{
string id;
string literal; // "CHHRT" or whatever;
int sequence;
con.Open();
string rate = "SELECT MAX(TypeID) FROM tblRoomTypeRate";
cmd = new OleDbCommand(rate, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
id = dr[0].ToString();
sequence = int.Parse( new string( id.Where( char.IsDigit ).ToArray() ) );
literal = new string( id.Where( char.IsLetter ).ToArray() );
id = literal + ( sequence + 1 ).ToString( "000" );
txtRateID.Text = id;
}
con.Close();
}
Related
I want make a auto number based date and number at "Transaction" Form. But i have problem with make a "condition" to compare date "today" and date "yesterday". If date is different, then will make a new "autonumber" from number 1. For example, that date is 2019-08-08 so the ID from "permintaanId" is P2019080803 (two last number is how many transaction make that day). And tomorrow is 2019-08-09 will make ID P2019080901 (two last number will reset because no one transaction make)
private void auto()
{
long hitung;
string urut;
SqlConnection conn = konn.GetConn();
conn.Open();
cmd = new SqlCommand("select permintaanId from permintaan_data where permintaanId in(select max(permintaanId) from permintaan_data) order by permintaanId DESC", conn);
rd = cmd.ExecuteReader();
rd.Read();
if (rd.HasRows) //<- this condition
{
hitung = Convert.ToInt64(rd[0].ToString().Substring(rd["permintaanId"].ToString().Length - 2, 2)) + 1;
string joinstr = "00" + hitung;
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + joinstr.Substring(joinstr.Length - 2, 2);
}
else
{
urut = "P" + DateTime.Now.ToString("yyyyMMdd") + "01";
}
rd.Close();
txt_noPermintaan.Text = urut;
conn.Close();
}
get last item created
cmd = new SqlCommand("select top1 permintaanId from permintaan_data order by DESC", conn);
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
var id = rd["the one with p and 2 numbers at the end"].ToString();
var dateLastCreated = id.ToString().Remove(0,1).Remove(id.Length-2,2);
if (dateLastCreated == DateTime.Now.ToString("yyyyMMdd"))
{
//increment
}
else
{
//create new
}
}
DECLARE #permintaanId INT=0
DECLARE #NewNo VARCHAR(40)=''
select #permintaanId=CAST(ISNULL(MAX(RIGHT(permintaanId,1)),0)+1 AS INT)
FROM permintaan_data
WHERE CAST([tranData] AS DATE) =CAST(GETDATE() AS DATE)
SET #NewNo='P'+CONVERT(VARCHAR(10),GETDATE(),112)+CAST(#permintaanId AS VARCHAR(10))
SELECT #NewNo
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();
}
Hi i am not sure how to retrieve all values with same id and display them in one label.
Example :
id food
1 chicken
1 fish
Desired output:
chicken,fish
How can i do that?
SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Label1.Text = reader["food"].ToString();
}
con.Close();
Label1.Text = string.Empty;
SqlConnection con1 = new SqlConnection(strConnString);
con.Open();
str = "select food from foodName where id= 1";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
Label1.Text += reader["food"].ToString();
}
con.Close();
You can just do a foreach and add form a string using StringBuilder,
StringBuilder test = new StringBuilder();
foreach(yourClassname test in yourList)
{
test.Append(test.name);
}
Use lambda expression in C#.
var list = new List<Product>(){
new Product {ID=1, FoodName ="chicken"},
new Product{ID=2, FoodName="egg"},
new Product{ID=1, FoodName="fish"}
};
var output = list.Where(s => s.ID == 1).Select(s=>s.FoodName).ToArray(); //result will be array of items.
Use string.Join to get output results "chicken,fish"
string.Join(",", output); //result will be chicken,fish
Since you can't provide us your code. I'm assuming you have a list of food [List<Food>] and you have an id and foodName inside of it. What you can do is this:
IEnumerable<string> selectedFood = foods.FindAll(food => food.id == 1).Select(food => food.foodName);
string result = string.Join(", ", selectedFood);
You can now use the result as your label's value.
Hope this helps!
If you need to concatenate all values:
String chickenVar = "Chicken";
String fishVar = "Fish";
String result = chickenVar +", " + fishVar;
I have a few labels on my site, which i need to populate with specific values from a database. So I've used a naming convention such as "lblx1", "lblx2", "lblx3" etc. and planned to do the following in a while loop:
lblx + id.Text = dbVariable
but this can't work as the code needs the name of an existing label in full.
public void beanList()
{
SqlCommand comm = new SqlCommand("SELECT id,Price250g,Price1kg FROM Beans", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
string id = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
lbl250 + id.Text = price250g;
lbl1 + id.Text = price1kg;
}
}
I have also attempted from an anwser:
public void beanList()
{
SqlCommand comm = new SqlCommand("SELECT id,Price250g,Price1kg FROM Beans", conn);
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
string id = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
Label l250g = new Label();
l250g.ID = "lbl250" + id;
l250g.Text = price250g;
Label l1kg = new Label();
l1kg.ID = "lbl1" + id;
l1kg.Text = price1kg;
}
}
But this does nothing, when stepping through "l250g.ID" is set, but "l250g.Text" doesn't work. It runs but is setting the text of the label whos ID it has been given.
Is there a way to get this to work without having to do a separate database query for each label, as the attempted while loop method is ideal as it would be fastest instead of calling the query X amount of times.
Create a List<string, Label>, like this:
List<KeyValuePair<string, Label>> elements = new List<KeyValuePair<string, Label>>();
Whenever you add an element, you do this:
elements.Add(new KeyValuePair<string, label>("lblx" + ids.Count, myLabel));
basically you need to find the control first. Hope the below code hint helps
string[] id = new string(1);
id[0] = reader["id"].ToString();
string price250g = reader["Price250g"].ToString();
string price1kg = reader["Price1kg"].ToString();
string templabel = null;
foreach (string i in id)
{
templabel = lbx + i;
var matches = this.Controls.Find(templabel, true).GetValue(0);
((Label)matches).Text = price250g;
}
I have specified GetValue(0) for my test. You can take a counter in your case.
My table structure is as follows:
Session
--------------
SessionID (PK)
RoomID
SessionDate
SessionTimeStart
SessionTimeEnd
I have a following query which will always return one row and display in DGV. I use DataAdapter for connection:
DataTable queryResult = new DataTable();
string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
SqlCommand command = new SqlCommand(query, MyConn);
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(queryResult);
I would like to save the query result into multiple strings representing table columns, i.e.
SessionIDstring = query result for SessionID column
RoomIDstring = query result for RoomID column
and so on...
Is it possible to achieve it using one query, or do I have to create 5 queries for each column?
Something similar to this, perhaps, using ADO.NET?
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
using (var connection = new SqlConnection(ConnStr))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
// Note that reader[x] has the equivalent type to the type
// of the returned column, converted using
// http://msdn.microsoft.com/en-us/library/cc716729.aspx
// .ToString() if the item isn't null is always ok
string SessionIDstring = reader[0].ToString(); // it should be an int
// reading it twice is ok
int RoomID = (int)reader[1]; // it should be an int
string RoomIDstring = reader[1].ToString(); // it should be an int
if (reader.Read())
{
throw new Exception("Too many rows");
}
}
else
{
throw new Exception("No rows");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This code was adapted from MSDN ADO.NET Code Examples. I added some usings and made it single row. I don't even want to know why MSDN examples don't go the full length with using.
Note that SqlDataAdapter are built to recover multiple rows/big data and put them in a DataSet. You can use them for single row data, but it's much easier to simply use a SqlDataReader if you only want to fill some variables.
declare #col1 int
declare #col2 varchar(42)
select #col1 = col1
, #col2 = col2
, ....
You could create a class like so...
public class SessionDto
{
public string SessionID {get; set;}
public string RoomID {get; set;}
public string SessionDate {get; set;}
public string SessionTimeStart {get; set;}
public string SessionTimeEnd {get; set;}
}
And then have a method that takes a Room ID and builds your session object
public SessionDto GetSessionData(int roomId)
{
using (var cnn = new SqlConnection(ConnStr))
{
SessionDto sessionDto;
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
cnn.Open();
using (var cmd = new SqlCommand(query,cnn))
{
cmd.Parameters.Add("#RoomID", SqlDbType.Char).Value = roomId;
using (var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
sessionDto = new sessionDto{
SessionID = rdr.GetString(0),
RoomID = rdr.GetString(1),
SessionDate = rdr.GetString(2),
SessionTimeStart = rdr.GetString(3),
SessionTimeEnd = rdr.GetString(4)
};
}
}
}
}
}
return sessionDto;
}
A lot of this is hand typed as I havent got access to VS right now,
but you should get it to work.
Also, I have used rdr.GetString(), there are other methods for GetType().