Object reference not set to an instance of object - c#

I have a function like this
public void GetTablesWithUpperCaseName()
{
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = txtHost.Text;
objConnectionString.UserID = txtUsername.Text;
objConnectionString.Password = txtPassword.Text;
objConnectionString.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);
SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString);
//To Open the connection.
sConnection.Open();
//Query to select table_names that have their names in uppercase letters.
string selectTablesWithUppercaseName = #"SELECT
NAME
FROM
sysobjects
WHERE
UPPER(name) COLLATE Latin1_General_BIN = name COLLATE Latin1_General_BIN
AND
OBJECTPROPERTY(ID,N'IsTable')=1
AND
OBJECTPROPERTY(ID,N'IsMSShipped')=0 ";
//Create the command object
SqlCommand sCommand = new SqlCommand(selectTablesWithUppercaseName, sConnection);
try
{
//Create the dataset
DataSet dsListOfTablesWithUppercaseName = new DataSet("sysobjects");
//Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectTablesWithUppercaseName, sConnection);
//Provides the master mapping between the sourcr table and system.data.datatable
sDataAdapter.TableMappings.Add("Table", "sysobjects");
//Fill the dataset
sDataAdapter.Fill(dsListOfTablesWithUppercaseName);
//Bind the result combobox with foreign key table names
DataViewManager dvmListOfForeignKeys = dsListOfTablesWithUppercaseName.DefaultViewManager;
dgResultView.DataSource = dsListOfTablesWithUppercaseName.Tables["sysobjects"];
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
finally
{
//If connection is not closed then close the connection
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Close();
}
}
}
And another function for counting the rows generated from the previous functions. But this function
Null Reference Exception or Object
reference not set to an instance of
object..
Can anyone help me in this... why it is catching error only for the functions above and working fine for all other similar functions.
private void UpdateLabelText()
{
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = txtHost.Text;
objConnectionString.UserID = txtUsername.Text;
objConnectionString.Password = txtPassword.Text;
objConnectionString.InitialCatalog = Convert.ToString(cmbDatabases.SelectedValue);
SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString);
//To Open the connection.
sConnection.Open();
try
{
int SelectedCellTotal = 0;
int counter;
// Iterate through the SelectedCells collection and sum up the values.
for(counter = 0;counter < (dgResultView.SelectedCells.Count);counter++)
{
if(dgResultView.SelectedCells[counter].FormattedValueType == Type.GetType("System.String"))
{
string value = null;
// If the cell contains a value that has not been commited,
if(dgResultView.IsCurrentCellDirty == true)
{
value = dgResultView.SelectedCells[counter].EditedFormattedValue.ToString();
}
else
{
value = dgResultView.SelectedCells[counter].FormattedValue.ToString();
}
if(value != null)
{
// Ignore cells in the Description column.
if(dgResultView.SelectedCells[counter].ColumnIndex != dgResultView.Columns["TABLE_NAME"].Index)
{
if(value.Length != 0)
{
SelectedCellTotal += int.Parse(value);
}
}
}
}
}
// Set the labels to reflect the current state of the DataGridView.
lblDisplay.Text = "There are Total " + dgResultView.RowCount + cmbOperations.SelectedItem.ToString();
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
finally
{
//If connection is not closed then close the connection
if(sConnection.State != ConnectionState.Closed)
{
sConnection.Close();
}
}
}
Also the lblDisplay.Text is not taking proper spaces.
Waiting for reply

OK, I don't really have an answer why you're getting a "null reference exception" - but a few points to throw in, nonetheless:
I would use sys.tables instead of sysobjects and having to specify what type of object to query for
ALWAYS put your disposable SqlConnection and SqlCommand into using(.....) { ...... } blocks. That way, you won't need any finally {..} blocks, and .NET will take care of properly disposing of those objects when they're no longer needed
why do you use a DataSet when you only have a single table inside?? That's just unnecessary overhead - use a DataTable instead!
don't open the SqlConnection that early - wait 'til the very last moment, open it, execute query, close it again right away
actually, when using the SqlDataAdapter, you don't need to open the SqlConnection yourself at all - the SqlDataAdapter will do that for you (and close it again after it is done reading the data)
do not mix the retrieval of the data from the database with the binding to the UI element - this is a very bad practice. From the GetTablesWithUpperCaseName method, you should return something (like a DataTable) to the caller (the UI) and let the UI handle the binding process
along the same lines: that method should not be grabbing stuff from UI elements (like text boxes) itself - pass in those values as method parameters, to get a cleaner code - one that you might actually be able to reuse in another project some day
This is how I think your first method ought to look like
public DataTable GetTablesWithUpperCaseName(string server, string database,
string username, string password)
{
// Create the datatable
DataTable dtListOfTablesWithUppercaseName = new DataTable("tableNames");
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = server;;
objConnectionString.UserID = username;
objConnectionString.Password = password;
objConnectionString.InitialCatalog = database;
// Define the Query against sys.tables - much easier and cleaner!
string selectTablesWithUppercaseName =
"SELECT NAME FROM sys.tables WHERE UPPER(name) COLLATE Latin1_General_BIN = name COLLATE Latin1_General_BIN AND is_msshipped = 0";
// put your SqlConnection and SqlCommand into using blocks!
using (SqlConnection sConnection = new SqlConnection(objConnectionString.ConnectionString))
using (SqlCommand sCommand = new SqlCommand(selectTablesWithUppercaseName, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectTablesWithUppercaseName, sConnection);
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfTablesWithUppercaseName);
}
catch (Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return dtListOfTablesWithUppercaseName;
}

Related

Passing Connection From TableAdapter Produces connectionstring property has not been initialized

I ran into a problem where passing a connection from a TableAdapter to some methods throws an exception stating the connectionstring isn't initialized. There are quite a few questions on SO with this exception but none were passing the connection and most were because the ConnectionString was null. Weird thing is I used MessageBox.Show(connection.ConnectionString); through out the chain of methods and I receive a valid connection string at every step. This is a somewhat complicated program that is in production but I will try to simplify the code for this question...
This is the postInventoryData method, which takes a DataGridView with inventory items and iterates through it posting them to the inventory. I use a TransactionScope to ensure the changes are safely rolled back in the event of an error. If an item is a kit(an item comprised of other items) I must iterate through those items and remove them from the inventory. The problem occurs when I check whether or not the item is a kit.
public bool postInventoryData(DataGridView dgv)
{
bool successful = true;
TestDataSetTableAdapters.inentoryTrxTableAdapter inventoryTrxAdapter =
new TestDataSetTableAdapters.inentoryTrxTableAdapter();
try
{
using (TransactionScope trxScope = new TransactionScope
(TransactionScopeOption.Required, new System.TimeSpan(0, 15, 0)))
{
MessageBox.Show(inventoryTrxAdapter.Connection.ConnectionString); // <-- Valid ConnectionString
inventoryTrxAdapter.OpenConnection();
for (int i = 0; i < dgv.Rows.Count; i++)
{
//parameter values
string departmentCode = dgv.Rows[i].Cells["Department_Code"].Value.ToString();
string machineCode = dgv.Rows[i].Cells["Machine_Code"].Value.ToString();
string operatorCode = dgv.Rows[i].Cells["Operator_Code"].Value.ToString();
string itemNumber = dgv.Rows[i].Cells["Item_Number"].Value.ToString();
double? qtyProduced = Convert.ToDouble(dgv.Rows[i].Cells["Quantity"].Value.ToString());
bool isKit =
businessLayer.isItemNumberKit
(inventoryTrxAdapter.Connection, itemNumber); // <-- CULPRIT!
// Inserts the item
dailyProductionInsertQty(
departmentCode,
machineCode,
operatorCode,
itemNumber,
isKit,
qtyProduced,
inventoryTrxAdapter,
trxScope);
}
inventoryTrxAdapter.CloseConnection();
trxScope.Complete();
}
}
catch (System.Exception ex)
{
successful = false;
MessageBox.Show(ex.ToString());
}
return successful;
}
The isItemNumberKit method
public bool isItemNumberKit(SqlConnection connection, string itemNumber)
{
bool contains;
MessageBox.Show(connection.ConnectionString); // <-- Valid ConnectionString
DataTable dt = getKit(connection, itemNumber); // <-- CULPRIT!
if (dt.Rows.Count > 0)
{
contains = true;
}
else
{
contains = false;
}
return contains;
}
The getKit method
public DataTable getKit(SqlConnection connection, string itemNumber)
{
DataTable dt = new DataTable();
SqlConnection myConnection = connection;
MessageBox.Show(myConnection.ConnectionString); // <-- Valid ConnectionString
SqlParameter paramItemNumber = new SqlParameter();
paramItemNumber.ParameterName = "#ItemNumber";
paramItemNumber.Value = itemNumber;
paramItemNumber.SqlDbType = System.Data.SqlDbType.VarChar;
try
{
using (myConnection)
{
string sql =
#"SELECT kits.Row_Id,
kits.Kit_Item_Number,
kits.Location_Code
FROM Inventory.dbo.Z_PV_Kits kits
WHERE kits.Kit_Item_Number=#ItemNumber";
//myConnection.Open();
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
{
myCommand.Parameters.Add(paramItemNumber);
SqlDataReader reader = myCommand.ExecuteReader();
dt.Load(reader);
}
}
}
catch (Exception ex)
{
dt = null;
MessageBox.Show(ex.ToString());
}
return dt;
}
When I execute postInventoryData the program throws an exception with the message, "The connectionstring property has not been initialized." with the line numbers pointing to isItemNumberKit and getKit. As you can see in the code above, I used a MessageBox.Show(connection.ConnectionString) throughout the process and each time I received a valid Connection string. I have created a workaround which stores a cached DataTable containing all the kit items I can run linq statements on. I am not in emergency mode or anything but I thought this to be weird and an opportunity for me to learn. Thanks in advance for any help!
It might be possible that you have 2 app.config files in your solution with 2 different connection strings.
OK, I figured it out and now when I think about it the answer was somewhat obvious. I always use using(){} blocks to ensure connections and similar objects are properly disposed and taken care of after they are used. The solution was to simply remove the using(myConnection){} block from the getKit method like this:
public DataTable getKit(SqlConnection connection, string itemNumber)
{
DataTable dt = new DataTable();
SqlConnection myConnection = connection;
MessageBox.Show(myConnection.ConnectionString);
SqlParameter paramItemNumber = new SqlParameter();
paramItemNumber.ParameterName = "#ItemNumber";
paramItemNumber.Value = itemNumber;
paramItemNumber.SqlDbType = System.Data.SqlDbType.VarChar;
try
{
string sql =
#"SELECT kits.Row_Id,
kits.Kit_Item_Number,
kits.Location_Code
FROM Inventory.dbo.Z_PV_Kits kits
WHERE kits.Kit_Item_Number=#ItemNumber
";
//myConnection.Open();
using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
{
myCommand.Parameters.Add(paramItemNumber);
SqlDataReader reader = myCommand.ExecuteReader();
dt.Load(reader);
}
}
catch (Exception ex)
{
dt = null;
MessageBox.Show(ex.ToString());
}
return dt;
}
This will leave the connection intact but properly dispose of the command. Sorry for the long winded question with a short simple answer. Hope this might help someone someday.

How to determine an existing oracle database connection in C#?

Assuming that I call the method below with the right credentials:
private bool Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
bool isConnected = false;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
isConnected = true;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
conn.Close();
}//finally
return isConnected;
}
I have successfully open the connection in my method below:
private bool ValidateUserCode(string usercode)
{
UserAccountDefine def = new UserAccountDefine();
UserAccountService srvc = new UserAccountService();
UserAccountObj obj = new UserAccountObj();
bool returnVal = false;
bool isValid = Connect(def.DB_DUMMY_USERCODE, def.DB_DUMMY_PASSWORD);
if (isValid)
{
obj.SQLQuery = string.Format(def.SQL_LOGIN, usercode.ToLower(), DateTime.Now.ToString("MM/dd/yyy"));
DataTable dt = srvc.Execute(obj, CRUD.READALL);
if (dt.Rows.Count == 1)
{
returnVal = true;
}
}
return returnVal;
}
The question is how can I determine the connection status in ValidateUserCode() method?
How can I close it afterwards?
Note:
I explicitly declare the string variables in UserAccountDefine(); so you don't have to worry about that.
I already tried declaring a new OleDbConnection conn inside the ValidateUserCode() to but the conn.State always returning "Closed".
UPDATE
I have a system with 2-layer security feature. 1st is in application and 2nd is on database. If a user logs in to the application, the username and password is also used to log him/her in to the database. Now, the scenario is when a user forgot his/her password, we can't determine the fullname, email and contact (which are maintained in the database) of the user. I just know his usercode. To determine the contact details, I have to open an active connection using a DUMMY_ACCOUNT.
Note that I never maintain the password inside the database.
First of all, you call Close() in your finally block, which means that at any point in your second method, the connection would be closed. Moreover, even if you don't Close() it,since conn is a local variable in Connect(), when you're back in ValidateUserCode(), the connection is already up for garbage collection, and when it's Dispose()d, it also closes automatically.
I sugges you either make it a member, pass it as an out parameter, return it by the Connect() method (and return null for failure, or something, if you don't like exceptions)..or redesign the code.
private OleDbConnection Connect(string username, string password)
{
string CONNSTRING = "Provider = MSDAORA; Data Source = ISDQA; User ID = {0}; Password = {1};";
OleDbConnection conn = new OleDbConnection();
string strCon = string.Format(CONNSTRING, username, password);
conn.ConnectionString = strCon;
try
{
conn.Open();
if (conn.State.ToString() == "Open")
return conn;
}//try
catch (Exception ex)
{
lblErr.Text = "Connection error";
}//catch
finally
{
//you don't want to close it here
//conn.Close();
}//finally
return null;
}
I am not sure how this information helps you.
I had similar problem while using OLEDB connection for Excel Reading. I didn't knew the answer. So, just I added a global variable for OleDbConnection initialized to null.
In my method, I used to check that null, if not close it and again open it.
if (con != null)
{
con.Close();
con.Dispose();
}
try
{
con = new OleDbConnection(connectionString);
}
catch (Exception ex)
{
MessageBox.Show("oledbConnection = " + ex.Message);
}
try
{
con.Open();
}
catch (Exception ex)
{
MessageBox.Show("connection open = " + ex.Message + "\n");
}
I could able to continue after this. You can try, if it works for you its good!
I'm not sure I follow the question quite right. My answer is based on the premise that you want to open/retrieve a connection, take an action, and close/release the connection afterward.
The code you include does not do that well. Typical DAO code resembles this pseudocode, in my case taken from some boilerplate code I use.
public DataSet FetchDataSet(string sql, IDictionary paramHash) {
var cnn = AcquireConnection();
var rtnDS = new DataSet();
try
{
var cmd = cnn.CreateCommand();
cmd.CommandText = sql;
SetParameters(cmd, paramHash);
IDbDataAdapter ida = new DataAdapter { SelectCommand = cmd };
LogSql(sql, paramHash, "FetchDataSet");
ida.Fill(rtnDS);
}
catch (Exception ex)
{
DebugWriteLn("Failed to get a value from the db.", ex);
throw;
}
finally
{
ReleaseConnection(cnn);
}
return rtnDS;
}
Note that the code above is strictly about communicating with the database. There is no assessment of whether the data is right or wrong. You might have a DAO that is a subclass of the one that contains the above code, and it might do this:
public MyItemType FindSomeValue(long Id)
{
const string sql = #"SELECT something from somewhere where id=:id";
var myParams = new Dictionary<string, long> { { "id", Id } };
var ds = FetchDataSet(sql, myParams);
return (from DataRow row in ds.Tables[0].Rows
select new Item
{
Id = Convert.ToInt64(row["ID"], CultureInfo.InvariantCulture),
Name = row["NAME"].ToString()
}).FirstOrDefault();
}
In fact, the above is pseudocode from a DAO implementation that I've used for years. It makes data access relatively painless. Note that there is some real code behind those methods like SetParameters (30 - 80 lines or so), and I have a bunch of other protected methods like FetchScalar, ExecuteSQL, etc.

Check for MS Access database table if not exist create it

How do you programmatically check for MS Access database table, if not exist then create it?
You could iterate though the table names to check for a specific table. See the below code to get the table names.
string connectionstring = "Your connection string";
string[] restrictionValues = new string[4]{null,null,null,"TABLE"};
OleDbConnection oleDbCon = new OleDbConnection(connectionString);
List<string> tableNames = new List<string>();
try
{
oleDbCon.Open();
DataTable schemaInformation = oleDbCon.GetSchema("Tables", restrictionValues);
foreach (DataRow row in schemaInformation.Rows)
{
tableNames.Add(row.ItemArray[2].ToString());
}
}
finally
{
oleDbCon.Close();
}
To check if a table exists you can extend DbConnection like this:
public static class DbConnectionExtensions
{
public static bool TableExists(this DbConnection conn, string table)
{
conn.open();
var exists = conn.GetSchema("Tables", new string[4] { null, null, table, "TABLE" }).Rows.Count > 0;
conn.close();
return exists;
}
}
Then you can call TableExists in any derived class like OleDbConnection, SQLiteConnection or SqlConnection.
Simply execute following code if table will exist it will return error other wise it will create a new one:
try
{
OleDbConnection myConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + frmMain.strFilePath + "\\ConfigStructure.mdb");
myConnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = myConnection;
myCommand.CommandText = "CREATE TABLE <yourtable name>(<columns>)";
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch(OleDbException e)
{
if(e.ErrorCode == 3010 || e.ErrorCode == 3012)
// if error then table exist do processing as required
}
Those error codes are returned if a table already exists - check here for all.
an easy way to do this is
public bool CheckTableExistance(string TableName)
{
// Variable to return that defines if the table exists or not.
bool TableExists = false;
// Try the database logic
try
{
// Make the Database Connection
ConnectAt();
// Get the datatable information
DataTable dt = _cnn.GetSchema("Tables");
// Loop throw the rows in the datatable
foreach (DataRow row in dt.Rows)
{
// If we have a table name match, make our return true
// and break the looop
if (row.ItemArray[2].ToString() == TableName)
{
TableExists = true;
break;
}
}
//close database connections!
Disconnect();
return TableExists;
}
catch (Exception e)
{
// Handle your ERRORS!
return false;
}
}
For completeness sake, I'll point out that a while back I posted 4 different ways of coding up a TableExists() function within Access. The version that runs a SQL SELECT on MSysObjects would work from outside Access, though in some contexts, you might get a security error (because you're not allowed to access the Jet/ACE system tables).

Controls are not inherited in winforms

I have a function of return type datatable
public DataTable GetAllPrimaryKeyTables(string ConnectionString)
{
// Create the datatable
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
//using(StringWriter sw = new StringWriter())
//{
// dtListOfPrimaryKeyTables.WriteXml(sw);
// sw.WriteLine();
// result = sw.ToString();
//}
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return dtListOfPrimaryKeyTables;
}
And I am calling it like this...
public class PrimaryKeyChecker : IMFDBAnalyserPlugin
{
public DataTable RunAnalysis(string ConnectionString)
{
return GetAllPrimaryKeyTables(ConnectionString);
}
In the IMFDBAnalyserPlugin I have
namespace MFDBAnalyser
{
public interface IMFDBAnalyserPlugin
{
DataTable RunAnalysis(string ConnectionString);
}
and on the main project background I have
private void btnStartAnalysis_Click(object sender, EventArgs e)
{
SqlConnectionStringBuilder objConnectionString = new SqlConnectionStringBuilder();
objConnectionString.DataSource = txtHost.Text;
objConnectionString.UserID = txtUsername.Text;
objConnectionString.Password = txtPassword.Text;
string[] arrArgs = {objConnectionString.ConnectionString};
string assemblyName = "PrimaryKeyChecker.dll";
Assembly assembly = Assembly.LoadFrom(assemblyName);
Type local_type = assembly.GetType("PrimaryKeyChecker.PrimaryKeyChecker");
MethodInfo objMI = local_type.GetMethod("RunAnalysis");
ConstructorInfo ci = local_type.GetConstructor(Type.EmptyTypes);
object responder = ci.Invoke(null);
object response = objMI.Invoke(responder, arrArgs);
But when I debug, the response object is returning only the empty datatable as I am unable to give the datasource in the first function because it is not inheriting controls there...
Hope the question is partially clear to you guys.. It should give the list of all tables when debugged but it is not taking the datagrid dgResultView there to give it a datasource...
This has nothing to do with inheritance; it looks like you are catching and logging exceptions:
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
I would start by looking there; most likely something is throwing, and telling you why... If I had to guess, it looks like maybe you are missing:
sConnection.Open();
The fact that anything is returned tells me it is just an exception.
Personally I would have just let an unanticipated exception bubble to the UI, and let the UI react by logging it and showing the appropriate #fail page.
Also, when possible, cast the plugin to the interface:
string assemblyName = "PrimaryKeyChecker.dll";
Assembly assembly = Assembly.LoadFrom(assemblyName);
Type local_type = assembly.GetType("PrimaryKeyChecker.PrimaryKeyChecker");
IMFDBAnalyserPlugin analyser =
(IMFDBAnalyserPlugin)Activator.CreateInstance(local_type);
DataTable response = analyser.RunAnalysis(objConnectionString.ConnectionString);

Using SqlDataReader to fill an ArrayList?

I'm trying to implement a method which will take a given connection string and return an ArrayList containing the contents of a SQL view.
I've verified the validity of the connection string and the view itself. However I don't see what the problem is in the code below. In debug, when it runs the ExecuteReader method and then try to enter the while loop to iterate through the records in the view, it immediately bails because for some reason sqlReader.Read() doesn't.
public ArrayList GetEligibles(string sConnectionString)
{
string sSQLCommand = "SELECT field1, field2 FROM ViewEligible";
ArrayList alEligible = new ArrayList();
using (SqlConnection sConn = new SqlConnection(sConnectionString))
{
// Open connection.
sConn.Open();
// Define the command.
SqlCommand sCmd = new SqlCommand(sSQLCommand, sConn);
// Execute the reader.
SqlDataReader sqlReader = sCmd.ExecuteReader(CommandBehavior.CloseConnection);
// Loop through data reader to add items to the array.
while (sqlReader.Read())
{
EligibleClass Person = new EligibleClass();
Person.field1 = sqlReader["field1"].ToString();
Person.field2 = sqlReader["field2"].ToString();
alEligible.Add(Person);
}
// Call Close when done reading.
sqlReader.Close();
}
return alEligible;
}
Note, EligibleClass is just a class object representing one row of the view's results.
A couple of things I would check:
Is the connection string ok
Does the user in your connection string have access to the database/view
Can you access that database from the pc your at
Does the ViewEligable view exist
Does the view contain a field1 and field2 column.
Here one way you could possibly clean up that code somewhat (assuming you have .net 2.0)
public List<EligibleClass> GetEligibles(string sConnectionString)
{
List<EligibleClass> alEligible = null;
try
{
using (SqlConnection sConn = new SqlConnection(sConnectionString))
{
sConn.Open();
using (SqlCommand sCmd = new SqlCommand())
{
sCmd.Connection = sConn;
sCmd.CommandText = "SELECT field1, field2 FROM ViewEligible";
using (SqlDataReader sqlReader = sCmd.ExecuteReader())
{
while (sqlReader.Read())
{
EligibleClass Person = new EligibleClass();
Person.field1 = sqlReader.GetString(0);
Person.field2 = sqlReader.GetString(1);
if (alEligible == null) alEligible = new List<EligibleClass>();
alEligible.Add(Person);
}
}
}
}
}
catch (Exception ex)
{
// do something.
}
return alEligible;
}

Categories

Resources