Good day Guys,
Trying to generate automatic Transaction ID. When there is an existing first record or more than one, the code below works fine. But if the table does not contain any data, it throws the error "Unable to cast object of type 'System.DBNull' to type 'System.String'."
Below is the code. Assist Please.
public string TransactionID()
{
string connString = CommonVariables.ConnectionString;
string sql = "SELECT MAX(Transaction_ID) FROM tbl_Transactions";
using (SqlConnection cnn = new SqlConnection(connString))
{
cnn.Open();
using (SqlCommand cmd = new SqlCommand(sql, cnn))
{
string max_ID = (string)cmd.ExecuteScalar();
if (max_ID == null || Convert.IsDBNull(max_ID.ToString()))
{
Transaction_ID = "17900000000001";
return Transaction_ID;
// MessageBox.Show("Maximum ID does not Exist", "Customer Exist", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
double newTransaction_ID = double.Parse(max_ID) + 1;
Transaction_ID = newTransaction_ID.ToString();
return Transaction_ID;
//MessageBox.Show("Maximum ID Exist, It is " + max_ID, "Customer Exist", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}