user1577711
user1577711

Reputation: 3

Return value of sql query to textbox in C#

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

Answers (5)

Damith
Damith

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

Soner Gönül
Soner Gönül

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

gregjer
gregjer

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

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33391

SqlCommand cmd = new SqlCommand("SELECT MAX(Account_No)  FROM addcustomer ", my);

Upvotes: 0

iabbott
iabbott

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

Related Questions