Error in OleDBConnection : Object reference not set to an instance of an object

pvsunil

New member
Joined
Apr 8, 2005
Messages
1
Programming Experience
3-5
I am running the following code. It executes when the value of variable i is 1 and when the loop continues and value of i becomes 2 i am getting error "Object reference not set to an instance of an object" in the cmdSearch.CommandText line. There is no problem with connection string. It successfully retrieves when i = 1. Can anybody help me out what is the problem. Please post with corrected code if anybody can help.
===========================================
for (int i=1; i <= objFolder.Items.Count; i++)
{
System.Data.OleDb.OleDbConnection odbSearch = new System.Data.OleDb.OleDbConnection();
System.Data.OleDb.OleDbCommand cmdSearch = new System.Data.OleDb.OleDbCommand();
odbSearch.ConnectionString = strConn;
cmdSearch.Connection = odbSearch;
item = (Outlook.ContactItem) objFolder.Items.Item(i);
string em = item.Email1Address;
cmdSearch.CommandText = "select * from Outlook_Contacts where FirstName='"+fn.ToString().Trim()+"' and LastName='"+ln.ToString().Trim()+"'";
odbSearch.Open();
OleDbDataReader rdrSearch = cmdSearch.ExecuteReader();
while( rdrSearch.Read())
{
RecordFlag = true;
}
odbSearch.Close();
}
===========================================
 
Well the first problem I see is that there are a lot of braces and semicolons in your code.
Just kidding, I realize that the code is C# (but this is a VB.NET site) :).

I can only imagine that you have left some code out as the line 'cmdSearch.Connection = odbSearch;' doesn't give the error but the 'cmdSearch.CommandText = ...' does. I would suggest placing a break-point and stepping through the code to check the value of cmdSearch. Or, if you have left out code, show that.

Good luck.
 
Back
Top