Reputation: 21
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MANINOTEBOOK\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Casesheet");
con.Open();
SqlCommand cmd = new SqlCommand("select PatientID from FTR where PatientID='" + textBox1.Text + "'", con);
textBox2.Text = cmd.ExecuteScalar().ToString();
if (textBox2.Text == textBox1.Text)
{
Consultation cs = new Consultation(textBox1.Text);
cs.Show();
}
else
{
MessageBox.Show("Data not found");
}
}
When i compile this code i get an error "NullReferenceException was unhandled". I dont know how to resolve it. I need to check the value generated in the "execute scalar" command is null or not. Kindly help me in resolving this problem.
Upvotes: 2
Views: 948
Reputation: 85
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=MANINOTEBOOK\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=Casesheet");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("select PatientID from FTR where PatientID='" + textBox1.Text + "'", con);
textBox2.Text = cmd.ExecuteScalar().ToString();
if (textBox2.Text == textBox1.Text)
{
Consultation cs = new Consultation(textBox1.Text);
cs.Show();
}
else
{
MessageBox.Show("Data not found");
}
}
catch(NullReferenceException ex)
{
Console.Write(ex.message);
}
}
you can catch your exception by putting try catch block and if you want to find out value generated then put breakpoint in code.
Upvotes: 0
Reputation: 460018
Most likely the exception was raised on ToString
:
textBox2.Text = cmd.ExecuteScalar().ToString();
That happens when no patient with that ID was found in database because then ExecuteScalar
returns null. So you should check for null:
Object patID = cmd.ExecuteScalar();
if(patID != null)
{
String patientID = patID.ToString();
// ...
}
Note: You should not concatenate strings to build your sql query but use SqlParameters
instead to avoid SQL-Injection.
Upvotes: 3
Reputation: 863
There is a difference* between .ToString() and Convert.ToString()
Convert.ToString() handles null values, i.e. If you give null input, it would give you back an empty string.
Whereas, .ToString() Which you've used - throws an exception when a null value is passed.
so, you could simply choose to rephrase your code like so:
textBox2.Text = cmd.ExecuteScalar().ToString();
** Not the only difference. Read more here: Difference between Convert.ToString() and .ToString()
Upvotes: 0
Reputation: 9418
cmd.ExecuteScalar()
this can return null if the result was empty. you should change it to
(cmd.ExecuteScalar() ?? "").ToString()
so it is changed to an empty string if it is null
Upvotes: 1