Reputation: 2855
This is a continution of my previous question: Could not find an implementation of the query pattern
Now I managed to query my database I can't seem to get the content on my webpage.
I try to return the code using the following code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Service1Client client = new Service1Client();
client.GetPersoonByIDCompleted += new EventHandler<GetPersoonByIDCompletedEventArgs>(client_GetPersoonByIDCompleted);
client.GetPersoonByIDAsync("1");
}
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
textBox1.Text = e.Error.ToString();
else
label1.Content = e.Result.Voornaam.ToString();
}
However when I press the button I get the following errors:
Object reference not set to an instance of an object.
at SilverlightApplication1.MainPage.client_GetPersoonByIDCompleted(Object sender, GetPersoonByIDCompletedEventArgs e) at SilverlightApplication1.ServiceReference1.Service1Client.OnGetPersoonByIDCompleted(Object state)
The weird thing is it works when I do not use LINQ, but normal SQL.
string sql = "SELECT ID, naam, voornaam, leeftijd FROM tblPersoon WHERE id=@pmID";
Persoon pers = null;
string connstr = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
using (SqlConnection cn = new SqlConnection(connstr))
{
SqlCommand com = new SqlCommand(sql, cn);
com.Parameters.AddWithValue("pmID", id);
cn.Open();
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
pers = new Persoon();
pers.ID = reader.GetString(0);
pers.Naam = reader.GetString(1);
pers.Voornaam = reader.GetString(2);
pers.Leeftijd = reader.GetInt32(3);
}
}
return pers;
}
LINQ result:
SQL result:
Thank you for helping me, I grealy appreciate it! Thomas
Upvotes: 0
Views: 207
Reputation: 20445
You get that particular exception by trying to reference the "e.Result" property when it's not valid, i.e., when the method call returned an exception instead of a value. Before you reference e.Result, confirm that e.Error == null, and if it doesn't, indulge yourself in some error handling or messaging code, e.g.:
void client_GetPersoonByIDCompleted(object sender, GetPersoonByIDCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show("An error occurred: " + e.Error.ToString());
}
else
{
label1.Content = e.Result;
}
}
Or something of that sort.
Upvotes: 2