0

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.

Leri
  • 12,367
  • 7
  • 43
  • 60
user2536447
  • 13
  • 3
  • 5
  • 8

3 Answers3

3

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;
2

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();
Alex G.P.
  • 9,609
  • 6
  • 46
  • 81
0

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();
Arulkumar
  • 12,966
  • 14
  • 47
  • 68