Click here to Skip to main content
14,357,121 members
Rate this:
Please Sign up or sign in to vote.
See more:
Please help me.

I wrote this code but it doesn't work.

What is my mistake and what is the correct code ?

protected void Page_Load(object sender, EventArgs e) 
{ 
  SqlCommand cmd = new SqlCommand(); 
  cmd.Connection = new SqlConnection(Class1.CnnStr);

  cmd.CommandText = "SELECT MAX(Code) FROM Customer"; 
  cmd.Connection.Open();   
  cmd.Parameters.AddWithValue(Code_lbl.Text,"@MAX(Code)"+1);   
  cmd.ExecuteNonQuery(); 
 }
Posted
Updated 29-Oct-11 4:44am
v3
Comments
Nueman 29-Oct-11 9:45am
   
Readability. Put code in block
kitykity 29-Oct-11 9:56am
   
How?please write it for me I don't know how to do this
Rate this:
Please Sign up or sign in to vote.

Solution 1

That doesn't work because it is thrown together from a variety of sources, without thinking too hard what you are doing.

SELECT MAX(Code) from Customer
Does not have any parameters so trying to add them is not going to help.
Even if it did, what is the value of a string plus the number one? Answer: a string with a "1" on the end. So your code
"@MAX(Code)"+1
is actually the same as
"@MAX(Code)1"
Your Label.Text almost certainly doesn't contain the name of a parameter in your SQL statement even if you actually had any.
cmd.ExecuteNonQuery();
Is a waste of time with a SELECT sql command because a SELECT command does not affect any rows in the table, it just returns them based on the selection criteria. Except that even if it did return any rows, you then throw then away, because ExecuteNonQuery returns the number of rows affected.

Without a better description of what you are actually trying to do, I can't tell you what is wrong with it, because everything is wrong - it doesn't do anything useful at all, so I can't tell what you were trying to do!
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

What Griff said.

Get rid of the cmd.Parameters. You have no parameters.

Also, your SQL query returns a discrete (single) value from the database. You want to use ExecuteScalar.

I am not going to code it for you, there are numerous references online. Google: "ExecuteScalar".
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100