AutoGenrate the code - c#

protected void Button1_Click(object sender, EventArgs e)
{
string cs = ConfigurationManager.ConnectionStrings["Dum01"].ConnectionString;
using (var scon = new SqlConnection(cs))
{
string codevalue = TextBox1.Text.Substring(0, 1);
var query = "SELECT MAX(CODE) AS TCODE FROM AgentMast WHERE LEFT(CODE,1)= #SearchText";
using (var cmd = new SqlCommand(query, scon))
{
cmd.Parameters.AddWithValue("#SearchText",codevalue);
cmd.CommandType = CommandType.Text;
cmd.Connection = scon;
scon.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
TextBox2.Text= sdr["TCODE"].ToString();
}
string codewithnumber = TextBox2.Text.Substring(1, 4);
Label2.Text = codewithnumber;
Label1.Text = (int.Parse(Label2.Text) + 1).ToString();
string firstchar=TextBox2.Text.Substring(0,1);
Label3.Text = firstchar + Label1.Text+"A" ;
}
scon.Close();
}
}
}
When in the textbox some text is entered then according to the first letter it selects the max code from AgentMast table. When I get the max code then I need to increment by one. For example if code found Z0001A then on next insert it should be Z0002A. 'A' is fixed for the agent table and also when TCODE is not found then I need to create new code with first character of textbox text and then 0001 and then fix character 'A'. How to solve? Thanks in Advance.

Try this:
oldCode = sdr["TCODE"].ToString();
if (string.IsNullOrEmpty(oldCode))
{
newCode = codevalue + "0001A";
}
else
{
int newIncrement = Convert.ToInt32(oldCode.Substring(1, 4)) + 1;
newCode = codevalue + newIncrement.ToString().PadLeft(4, '0') + oldCode.Substring(5, 1);
}

Related

C# 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException'

Have the error 'dbConn.ServerVersion' threw an exception of type 'System.InvalidOperationException, however VisualStudio does not pause the program and throw the exception at me. Here is the code:private void BTN_NA_Click(object sender, EventArgs e)
{
if (TXT_NAUN.Text != "" && TXT_NAPW.Text != "" && TXT_NAPW2.Text != "")
{
if (TXT_NAPW.Text == TXT_NAPW2.Text)
{
string input = TXT_NAPW.Text;
int hash = 0;
int output = 0;
foreach (char chara in input)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
output = output + temp;
output = output * 2;
}
hash = output % 1000;
OleDbConnection dbConn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=BHShooterProjectDB.accdb");
string sql = "SELECT Accounts.PlayerID FROM Accounts ORDER BY Accounts.PlayerID DESC ";
///string comm = "SELECT Accounts.PlayerID from Accounts";
/// INNER JOIN Leaderboard ON Leaderboard.PlayerID = Accounts.PlayerID WHERE Accounts.PlayerUsername = #ip";
OleDbCommand cmd = new OleDbCommand(sql, dbConn);
string result = "";
dbConn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
result = reader[0].ToString();
}
dbConn.Close();
{
string comm = "INSERT INTO Accounts (PlayerUsername, PlayerPassword, PlayerID, PlayerInvID) VALUES (#NAUN, #HPW, #NAPI, #NAPI)";
OleDbCommand command = new OleDbCommand(comm, dbConn);
command.Parameters.AddWithValue("#NAUN", TXT_NAUN.Text);
command.Parameters.AddWithValue("#HPW", hash);
foreach (char chara in result)
{
int temp = 0;
temp = System.Convert.ToInt32(chara);
result = result + temp;
}
result = result + 1;
command.Parameters.AddWithValue("#NAPI", result);
command.Parameters.AddWithValue("#NAPI", result);
dbConn.Open();
int rowsAffected = cmd.ExecuteNonQuery(); ///error appears here
dbConn.Close();
}
}
}
}
Any suggestions on solution, have tried a lot and this is my last hope!
Thanks,
Blackclaw_
At the line you got the error, you are using cmd (the select command). I think you want to use command (the insert command).

c# - 'input string was not in a correct format' when parsing integers

Okay, so i'm trying to get 18 "prices" from my database in SQL, then setting them in a local array. So far i have this logic in the data retrieval:
private void dbPrices()
{
string myConnectionString;
myConnectionString = "server=127.0.0.1;uid=root;" +
"pwd=;database=phvpos";
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = myConnectionString;
conn.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
for (int i = 1; i < 19; i++)
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT price from products where id = '" + i + "'";
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
pr[i] = reader.ToString();
prods[i] = int.Parse(pr[i]);
}
}
}
And this logic in getting the total amount:
private void btnTotal_Click(object sender, EventArgs e)
{
dbPrices();
itemcost[0] = Convert.ToInt32(txtRice.Text) * prods[0];
itemcost[1] = Convert.ToInt32(txtAdobo.Text) * prods[1];
itemcost[2] = Convert.ToInt32(txtIgado.Text) * prods[2];
itemcost[3] = Convert.ToInt32(txtSisig.Text) * prods[3];
...
itemcost[18] = itemcost[0] + itemcost[1] + itemcost[2] + itemcost[3] + itemcost[4] + itemcost[5]
+ itemcost[6] + itemcost[7] + itemcost[8] + itemcost[9] + itemcost[10]
+ itemcost[11] + itemcost[12] + itemcost[13] + itemcost[14] + itemcost[15]
+ itemcost[16] + itemcost[17];
int totalPrice = itemcost[18];
lblTotal.Text = Convert.ToString(totalPrice);
}
this line in dbPrices() spits out a 'input string was not in a correct format' error:
while (reader.Read())
{
pr[i] = reader.ToString();
prods[i] = int.Parse(pr[i]);
}
I have also tried:
while (reader.Read())
{
prods[i] = Convert.toInt32(reader.ToString());
}
But also spits the same error. Is there anything that i'm doing wrong?
Try this. I find that when using 'reader' that even when your query only grabs one value you still need to specify what value your looking for.
prods[i] = int.Parse(reader["price"]);
and if price is nullable in the database use a ternary operator
prods[i] = reader["price"] == DBNull.Value ? 0 : int.parse(reader["price"]);
The value from your result needs to convert to int and your for loop block might cause you serious problem in the future, you might want to have a projection query and then assign the values of the result.
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = $"SELECT price FROM products WHERE id BETWEEN 1 AND 18"; //use projection. if you have a dynamic product id set, you can use IN in query.
MySqlDataReader reader = cmd.ExecuteReader();
var counter = 0; //counter
while (reader.Read())
{
prods[counter] = Convert.ToInt32(reader["price"]); //convert the result first then assign it to the item.
counter++;
}

Is my logic correct? I'm trying to calculate the total amount of each loop that's being read in a foreach loop?

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 1 calculated answer into a database.
private void btnSubmitConsultation_Click(object sender, EventArgs e)
{
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.calculateTotal(cMedication, cQuantity, cAppointment);
}
}
}
private void calculateTotal(string cMedication, string cQuantity, string cAppointment)
{
string strConnectionString = ConfigurationManager.ConnectionStrings["HConnection"].ConnectionString;
SqlConnection con = new SqlConnection(strConnectionString);
string insertPayment = "INSERT INTO PAYMENT (amount, appointmentID) " +
"VALUES (#insertAmount, #insertAppointment)";
using (SqlConnection connection = new SqlConnection(strConnectionString))
{
using (SqlCommand cmdPayment = new SqlCommand(insertPayment, connection))
{
string strPrice = "SELECT medicationPrice FROM MEDICATION WHERE medicationName= #getName";
SqlCommand cmdPrice = new SqlCommand(strPrice, con);
cmdPrice.Parameters.AddWithValue("#getName", cMedication);
con.Open();
SqlDataReader readPrice = cmdPrice.ExecuteReader();
if (readPrice.Read())
{
string getPrice = readPrice["medicationPrice"].ToString();
double doublePrice = Convert.ToDouble(getPrice);
double doubleQuantity = Convert.ToDouble(cQuantity);
double result = doublePrice * doubleQuantity;
for (int i = 0; i < dataPrescription.Rows.Count; i++)
{
double total = result * i;
string answer = result.ToString();
MessageBox.Show(answer);
cmdPayment.Parameters.AddWithValue("#insertAmount", answer);
}
}
readPrice.Close();
con.Close();
cmdPayment.Parameters.AddWithValue("#insertAppointment", txtAppointmentID.Text);
connection.Open();
cmdPayment.ExecuteNonQuery();
connection.Close();
}
}
}
You have to change the command text to be the insert statement.
connection.Open();
cmdPayment.CommandText = insertPayment;
cmdPayment.ExexuteNonQuerry();

where I am wrong? creating labels dynamically c#

I created labels and textboxes dynamically . everything goes fine,but the second label doesn't want to appear at all. where i am wrong? this is my code in C#:
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
OracleDataReader reader;
int x = 434;
int y = 84;
int i = 0;
try
{
conn.Open();
foreach (var itemChecked in checkedListBox1.CheckedItems)
{
Label NewLabel = new Label();
NewLabel.Location = new Point(x + 100, y);
NewLabel.Name = "Label" + i.ToString();
Controls.Add(NewLabel);
TextBox tb = new TextBox();
tb.Location = new Point(x, y);
tb.Name = "txtBox" + i.ToString();
Controls.Add(tb);
y += 30;
OracleCommand cmd = new OracleCommand("SELECT distinct data_type from all_arguments where owner='HR' and argument_name='" + itemChecked.ToString() + "'", conn);
reader = cmd.ExecuteReader();
while (reader.Read())
{
label[0].Text = reader["data_type"].ToString();
}
i++;
}
}
finally
{
if (conn != null)
conn.Close();
}
}
private void Procedure()
{
string proc = "";
try
{
conn.Open();
if (this.listView1.SelectedItems.Count > 0)
proc = listView1.SelectedItems[0].Text;
OracleCommand cmd = new OracleCommand("" + proc + "", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 600;
int i = 0;
foreach (var itemChecked1 in checkedListBox1.Items)
{
Control[] txt = Controls.Find("txtBox" + i.ToString(), false);
Control[] label = Controls.Find("Label" + i.ToString(), false);
cmd.Parameters.Add(new OracleParameter("select distinct data_type from all_arguments where owner='HR' and argument_name=toupper("+itemChecked1.ToString()+")",conn));
cmd.Parameters[":"+itemChecked1.ToString()+""].Value=label[0].Text;
cmd.Parameters.Add(new OracleParameter(":" + itemChecked1.ToString() + "", OracleDbType.Varchar2));
cmd.Parameters[":" + itemChecked1.ToString() + ""].Value = txt[0].Text;
i++;
I think the second Label has appeared. But its text is an empty string! So you will never see it.
Check the "data_type" returned by DB reader.

Is it possible to use ExecuteReader() twice?

I'm programming a database manager for a gameserver called OTServer, and I'm having problems using executereader() the second time. Here's code:
private void button1_Click(object sender, EventArgs e)
{
Form1 f = new Form1();
MySqlConnection conn = new MySqlConnection();
conn.ConnectionString = "Server=" + f.GetText1().Text + ";Username=" + f.GetText2().Text + ";Pwd=" + f.GetText3().Text + ";Database=" + f.GetText4().Text + ";";
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `players` WHERE name = #Name", conn);
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
MySqlDataReader Reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
while (Reader.Read())
{
label7.Text = (string)Reader[1];
label7.Show();
label8.Text = Reader[5].ToString();
label8.Show();
if ((int)Reader[6] == 1)
{
label9.Text = "Sorcerer (1)";
}
if ((int)Reader[6] == 2)
{
label9.Text = "Druid (2)";
}
if ((int)Reader[6] == 3)
{
label9.Text = "Paladin (3)";
}
if ((int)Reader[6] == 4)
{
label9.Text = "Knight (4)";
}
if ((int)Reader[6] == 0)
{
label9.Text = "None (0)";
}
label9.Show();
if ((int)Reader[3] == 1)
{
label10.Text = "Player";
}
if ((int)Reader[3] == 2)
{
label10.Text = "Tutor";
}
if ((int)Reader[3] == 3)
{
label10.Text = "Senior Tutor";
}
if ((int)Reader[3] == 4)
{
label10.Text = "Gamemaster";
}
if ((int)Reader[3] == 5)
{
label10.Text = "Community Manager";
}
if ((int)Reader[3] == 6)
{
label10.Text = "God";
}
if ((int)Reader[3] < 1 || (int)Reader[3] > 6)
{
label10.Text = "Unknown";
}
label10.Show();
label13.Text = "Account: " + Reader[4].ToString();
label13.Show();
}
Reader.Close();
cmd = new MySqlCommand("SELECT * FROM accounts WHERE id = #Account_ID", conn);
cmd.Parameters.AddWithValue("#Account_ID", label13.Text);
Reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
while (Reader.Read())
{
label11.Text = (string)Reader[0];
label11.Show();
}
Reader.Close();
}
Suggested solution: Try putting a using block around your DataReader, or call Dispose on it:
using (DataReader Reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
// ...do something with your data reader... then finish by:
Reader.Close();
} // <-- Reader.Dispose() called automatically at the end of using block.
// ...prepare second command...
// the same again for the second command:
using (DataReader Reader = cmd.ExecuteReader(CommandBehavior.SingleRow))
{
// ...
Reader.Close();
}
Assumed cause of your problem: The DB connection object may do some internal book-keeping to keep track of data readers. I've found out in a similar scenario that you're only allowed one DataReader at a time. So I believe the problem with your code is that, while you Close the Reader, you haven't explicitly Disposed it, so the connection object thinks the first data reader is still in use when you execute the second one.
Besides... why not simplify this code:
if ((int)Reader[6] == 1)
{
label9.Text = "Sorcerer (1)";
}
if ((int)Reader[6] == 2)
{
label9.Text = "Druid (2)";
}
...
to a switch statement?:
int x = (int)(Reader[6]);
string label9Text = string.Empty;
switch (x)
{
case 1: label9Text = "Sorcerer (1)"; break;
case 2: label9Text = "Druid (2)"; break;
...
}
label9.Text = label9Text;
(That would save you quite a bit of repetitive typing.)
Well, assuming that your code is correct you shouldn't have problem in executing two readers as you show in your code. Maybe you have problems because of not disposing commands or something else. I recommend an approach like this (Example made with Northwind db):
using (SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=SSPI;"))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM Orders", connection))
{
using (SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SingleRow))
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(2));
}
}
}
using (SqlCommand command = new SqlCommand("SELECT * FROM Products", connection))
{
using (SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SingleRow))
{
while (reader.Read())
{
Console.WriteLine(reader.GetString(1));
}
}
}
}
You should clean your code when recognizing the type of player. Create an enum instead:
public enum PlayerType
{
None = 0,
Sorcerer = 1,
Druid = 2,
Paladin = 3
}
And then do the following while reading:
PlayerType playerType = (PlayerType)reader.GetInt32(6);
label9.Text = playerType.ToString();

Categories

Resources