Reputation: 3
I want to access the last value in database column increment it by 1 and show on a textbox I used this code but nothing is displayed on text box what's wrong with this code?
SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No] FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar());
textBox1.Text = result.ToString();
Upvotes: 0
Views: 4741
Reputation: 63105
you can change the sql statement as below
SELECT MAX(Account_No) + 1 FROM addcustomer
or increment after selecting value by code
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar()) +1;
Final Code would be :
try
{
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) + 1 FROM addcustomer", con))
{
con.Open();
int result = (int)cmd.ExecuteScalar();
textBox1.Text = result.ToString();
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.ToString()); // do you get any Exception here?
}
Upvotes: 0
Reputation: 98868
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);
int result = ((int)cmd.ExecuteScalar()) + 1;
textBox1.Text = result.ToString();
Upvotes: 2
Reputation: 2843
You have wrongly placed bracket. Change this
SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No] FROM addcustomer ", my);
into that
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);
Upvotes: 1
Reputation: 33391
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer ", my);
Upvotes: 0
Reputation: 881
Looks like you're missing a bracket:
SqlCommand cmd = new SqlCommand("SELECT (MAX[Account_No] FROM addcustomer ", my);
should be
SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No) FROM addcustomer", my);
Upvotes: 0