Reputation: 43
I am using this code to check and prevent duplicate names when I insert names in a database table. So if the name exists it will prevent the insert and a MessageBox will be displayed warning that the name exists. if not, a MessageBox is displayed confirming the operation is done.
string Coonstring = "datasource=localhost;port=3306;username=root;password=****;Charset=utf8";
using (MySqlConnection connectionDatabase = new MySqlConnection(Coonstring))
{
try
{
connectionDatabase.Open();
using (MySqlCommand select = new MySqlCommand("SELECT COUNT(*) FROM project.name_registry WHERE Name=@NM", connectionDatabase))
{
select.Parameters.AddWithValue("@NM", txt.Text);
if (select.ExecuteScalar() != 0)
{
MessageBox.Show("Name exists");
return;
}
}
using (MySqlCommand cmddata = new MySqlCommand("INSERT INTO project.name_registry (name) VALUES(@NM)", connectionDatabase))
{
cmddata.Parameters.AddWithValue("@NM", txt.Text);
cmddata.ExecuteNonQuery();
MessageBox.Show("Done");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
My problem is when I run the code above, the following error is thrown
Specified cast is not valid.
What does this mean?
Upvotes: 0
Views: 183
Reputation: 2337
Maybe something like this?
var count = 0;
var obj = select.ExecuteScalar();
if(obj != null)
{
count = Convert.ToInt32(obj);
if(count != 0)
{
MessageBox.Show("Name exists");
return;
}
}
else
{
throw new Excepion();
}
Upvotes: 0
Reputation: 736
use parse or cast
if ((Int32)select.ExecuteScalar() != 0)
{
MessageBox.Show("Name exists");
return;
}
or
if(int.parse(select.ExecuteScalar().ToString())!=0)
{
MessageBox.Show("Name exists");
return;
}
Upvotes: 0
Reputation:
if (select.ExecuteScalar() != 0)
{
MessageBox.Show("Name exists");
return;
}
use
if(int.Parse(select.ExecuteScalar()) !=0)
Upvotes: 1
Reputation: 661
Both with parse
if (int.Parse(select.ExecuteScalar()) != 0)
{
MessageBox.Show("Name exists");
return;
}
or casting
if (((int)select.ExecuteScalar()) != 0)
{
MessageBox.Show("Name exists");
return;
}
should work.
Upvotes: 0