Below I give you some advice on your code. However I have grave concerns about this function. It looks as if you are attempting to find the maximum current id in order to assign the next value. This is a very bad design! What if another user adds another record while this code is running? (Very likely in multi-user environments). Far better is to use the right tool for the job - an
Identity column[
^] on the database
Code Review:
First look at the line
FunGetMaxID() = (reader["id"]);
That is very VB6 in style and will result in the compile error
Quote:
The left-hand side of an assignment must be a variable, property or indexer
Next - learn about the
using statement[
^] - it is especially useful for working with sql connections. You do not need to explicitly close the connection nor Dispose of it.
While we're on that subject, look at
con = new SqlConnection(cs.Dbcon);
con.Close();
There is no point in that
.Close()
- you have only just created the object!
Now consider your sql statement
SELECT ISNULL(MAX(ClassId),0)+1 AS Id FROM Class
It is better to handle the potential to be null at the source rather than escalating a null up calculations/functions/etc i.e. this would be better
SELECT MAX(ISNULL(ClassId,0)) AS Id FROM Class
The next problem is that you have
private string FunGetMaxID ()
but the maximum Id is likely to be an integer, so you should be returning an integer from your function. Note as well, the way you have named the function implies that you want the existing maximum value for id - but you are returning the maximum plus 1. Either rename your function or return the correct value
As Manas_Kumar has suggested, it is more appropriate to use
ExecuteScalar[
^] in this instance (you don't
have to, it's just more appropriate)
Regarding the Try-Catch block, you may also find these articles useful:
Exception Handling Best Practices in .NET[
^] and
Best Practices for Exceptions - MSDN[
^]
I would do something like
private int FunGetMaxID()
{
var maxId = 0;
try
{
using (var con = new SqlConnection(cs.Dbcon))
{
con.Open();
const string sql = "Select max(IsNull(ClassId,0)) as Id from Class ";
using (var cmd = new SqlCommand(sql, con))
{
cmd.CommandType = CommandType.Text;
maxId = (int)cmd.ExecuteScalar();
}
}
}
catch (SqlException ex)
{
MessageBox.Show("Error", "Message" + ex.Message);
}
return maxId;
}