Click here to Skip to main content
15,913,487 members
Please Sign up or sign in to vote.
1.00/5 (1 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 ?

C#
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 3: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

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

SQL
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.
C#
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!
 
Share this answer
 
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".
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900