简体   繁体   中英

Error Specified cast is not valid

I have the below function

SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
int h = (int)cmd.ExecuteScalar() + 1;
txtID.Text = h.ToString();
cn.Close();

How to fix this Error:

Specified cast is not valid.

given your code I feel the easiest way to fix the logic is to edit the SQL to

select ISNULL(max(ID),0) from EP_PATTERNS

To better understand what this does you can run this SQL in SSMS:

DECLARE @table table (ID int);
SELECT MAX(ID) FROM @table;
SELECT ISNULL(MAX(ID), 0) FROM @table;

Whether table EP_PATTERNS contains any rows? Otherwise you a trying to cast NULL to int and fails.

You code should looks like:

SqlConnection cn = new SqlConnection(constring);
cn.Open();
SqlCommand cmd = new SqlCommand("select max(ID) from EP_PATTERNS ", cn);
var value = (int?)cmd.ExecuteScalar();
int maxId = value.HasValue ? value.Value + 1 : 0;  //Increase value or default it to zero
txtID.Text = maxId.ToString();
cn.Close();

Using coalesce you can achieve this:

con.Open();
cmd.Connection = con;
cmd.CommandText = "select coalesce(max(user_id),0)+1 from user_master";
int user_id = int.Parse(cmd.ExecuteScalar().ToString());
txt_user_id.Text = user_id.ToString();
con.Close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM