问题
I sometimes get two different of error when executing OdbcDataAdapter.Fill(DataTable). Here is the code example:
string odbc = "select item, upcno from table";
OdbcCommand cmd = new OdbcCommand(odbc, fconn);
OdbcDataAdapter oda = new OdbcDataAdapter(cmd);
oda.Fill(dt);
System.NullReferenceException: Object reference not set to an instance of an object.
System.InvalidOperationException: No data exists for the row/column.
Does anyone have clue to resolve this problem?
回答1:
Not sure where you get connection object from your question but you can do as below. don't create class level connections, you can create it when you want and properly dispose it at the end.
public DataTable GetDataTableFromAdapter(string queryString)
{
DataTable dt = new DataTable();
using (OdbcConnection connection =
new OdbcConnection(ConnectionString))
{
using (OdbcDataAdapter adapter =
new OdbcDataAdapter(queryString, connection))
{
connection.Open();
adapter.Fill(dt);
}
}
return dt;
}
Call it as
DataTable dt = GetDataTableFromAdapter("select [item], [upcno] from [table]");
来源:https://stackoverflow.com/questions/16968124/error-from-odbcdataadapter-fill