|
The error is when you try and convert the return to a double, the return may be null. Change the return object (currently branchExposureFactor) to an object type and test it for null before trying to convert it to double.
double.TryParse would have caught the error.
Always test for null when using any object.
Do a little research on "Little Bobby Tables" otherwise he will trash you database!
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
If the rest of your application is written in a similar manner you are heading for serious trouble. Your SQL is wide open to injection attacks, you are not checking the user's input values and you are ignoring the possibility that any command could fail. You should rewrite the above to do the following:
- Check the content of the textboxes to see that they contain valid data.
- Use proper parameterised SQL queries.
- Split your SQL query into two parts so you first find whether the
BranchID query returns a good result. - Using the value returned from the
BranchID query, check the return value of the second query for the BranchExposureFactor . - Use the
double.TryParse() method to check that you have a valid floating point value.
Use the best guess
|
|
|
|
|
OleDbConnection dbConnDest;
dbConnDest = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= SystemA.accdb");
string query_select = "SELECT ReferenceYear FROM [MS Access;DATABASE=" + dialog.FileName + "].Questionnaires_Table1 Where ReferenceYear = '" + txtdateref.Text + "';";
OleDbCommand cmd_year = new OleDbCommand(query_select, dbConnDest);
dbConnDest.Open();
string rfyear = cmd_year.ExecuteScalar().ToString();
if (rfyear == null) { MessageBox.Show(" file not found with this ref year ", "", MessageBoxButtons.OK); }
dbConnDest.Close();
i have error in following row
string rfyear = cmd_year.ExecuteScalar().ToString();
if the query is wrong appears the error:
------------------------------------------
Object reference not set to an instance of an object.
|
|
|
|
|
zebra88 wrote: Object reference not set to an instance of an object.
And that is exactly the same cause/reason as your original problem.
|
|
|
|
|
zebra88 wrote: string rfyear = cmd_year.ExecuteScalar().ToString(); The line contains multiple statements.
object result = cmd_year.ExecuteScalar();
if (DBNull.Value == result || null == result)
throw new ApplicationException("Panic Now!");
string rf_year = Convert.ToString(result); Put a breakpoint on the first line (place the cursor there and press F9), step trough the code (Hit F5 to run, hit F11 to step once you hit the breakpoint). On the second line of this example, examine the value of the result -variable by hovering your mouse above it in the IDE.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
i have 2 connectionstring in c# and 2 connection with 2 different access database
in this query i use only one access db and one connection string but when i run the program it appears an error that say that could not found file dbfile.accdb
what is the problem ?
public bool findrefyear( string refyear)
{
bool findyear = false;
//create new new access connection to the database
OleDbConnection connd = new OleDbConnection(connection2);
//Set the access command string
OleDbCommand Cmd = new OleDbCommand("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "';", connd);
try
{
connd.Open();
Cmd.ExecuteNonQuery();
connd.Close();
findyear = true;
}
catch (OleDbException e)
{
MessageBox.Show(e.Message.ToString());
}
i call the above code with this code:
-----------------------------------------
...
if (txtdateref.Text != "" )
{
bool find_data = qhandler.findrefyear(txtdateref.Text);
if (find_data == false)
{
MessageBox.Show(" the record is not here ", "", MessageBoxButtons.OK);
}
else{
MessageBox.Show(" the record is here ", "", MessageBoxButtons.OK);
}
}
|
|
|
|
|
zebra88 wrote: what is the problem ?
Dunno. Does "error" mean that it throws an exception that the access database cannot be found? If yes, then there's an error in your connectionstring. If no, does "error" mean that it displays the message "the record is not here"?
Further, a "select" statement is a query. One would use the ExecuteReader method to read the dataset.
Bastard Programmer from Hell
If you can't read my code, try converting it here[^]
|
|
|
|
|
string rfyear = cmd_year.ExecuteScalar().ToString();
You are calling ToString() on the result of the call to ExecuteScalar() , and if that has returned null you will get the error you see. I Would suggest you re-read my previous suggestions, and the documentation for these methods, and start reorganising your code to include more robust error checking.
Also, please put <pre> tags around your code, as I have done here, to make it more readable.
Use the best guess
|
|
|
|
|
i change my code now and looks like the following:
now i have 2 connectionstring in c# and 2 connection with 2 different access database
in this query i use only one access db and one connection string but when i run the program it appears an error that say that No database specified in connection string or IN clause.
what is the problem ?
public bool findrefyear( string refyear)
{
bool findyear = false;
//create new new access connection to the database
OleDbConnection connd = new OleDbConnection(connection2);
//Set the access command string
OleDbCommand Cmd = new OleDbCommand("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "';", connd);
try
{
connd.Open();
Cmd.ExecuteNonQuery();
connd.Close();
findyear = true;
}
catch (OleDbException e)
{
MessageBox.Show(e.Message.ToString());
}
i call the above code with this code:
-----------------------------------------
...
if (txtdateref.Text != "" )
{
bool find_data = qhandler.findrefyear(txtdateref.Text);
if (find_data == false)
{
MessageBox.Show(" the record is not here ", "", MessageBoxButtons.OK);
}
else{
MessageBox.Show(" the record is here ", "", MessageBoxButtons.OK);
}
}
modified 7-Jul-13 10:51am.
|
|
|
|
|
zebra88 wrote: an error that say that No database specified in connection string or IN clause. So what is the content of your connection string?
Use the best guess
|
|
|
|
|
the content of connection string is a access database file that i don't want to locally connect with my c# because it is updated every time and user can import to the program with reference year the records that associated with this year i try to make it locally connected in c# and i observe that the database does not updated when i make it import again from my desktop on my laptop so the database that it is locally connected to my c# program has old record in spite of the two file it is the same but on different locations (locally- desktop and the other can be import to c#) .
i use the following query to get the records with the associated reference year but i have the problem that i said previous :
public DataTable findref2(string refyear)
{
try
{
//create new new connection to the database
OleDbConnection conn = new OleDbConnection(connectionstringA);
//Set the command string
string Cmd = ("SELECT ReferenceYear FROM Questionnaires_Table1 Where ReferenceYear = '" + refyear + "' ");
//create new data adapter
OleDbDataAdapter Adapter = new OleDbDataAdapter(Cmd, conn);
//create new command builder
OleDbCommandBuilder sqlCmdBuilder = new OleDbCommandBuilder(Adapter);
dTable = new DataTable();
Adapter.Fill(dTable);
conn.Close();
}
catch (OleDbException e)
{
MessageBox.Show(e.ToString());
}
//return the search results on a datatable
return dTable;
}
how can i get data without make my database locally connected in my c# program and i have the possibility to get data when i import from anywhere on my laptop to c# program. i have already a form that i put the reference year and opened a window that i can choose the access db file and i can import to my c# program (because i move on my locally connected access database which is different from database i make import ) but only if the year i put previous is on access db file i choose. Now i try to make a select query to check if the reference year already exists on file but i have the error No database specified in connection string or IN clause maybe because i must make locally connection on c# but i don't want as i said previous.
can you help me please?
modified 7-Jul-13 15:31pm.
|
|
|
|
|
I'm not sure that I understand completely but it sounds as if you are trying to access a database file by copying it from one location to another before extracting or updating its records. You would be better using a database system that you can access remotely, like SQL Server.
zebra88 wrote: but i have the error No database specified in connection string or IN clause And again I would ask, what is the actual content of your connection string? Using your debugger would help you diagnose this problem much faster than posting questions here.
Use the best guess
|
|
|
|
|
Hello,
I am currently creating an application that connects to a SQL database with approximately 800 rows.
The database is currently taking approximately 30 seconds to return any data when I run any sort of SELECT query. I was wondering if anyone had any ideas as to why?
Here is an example:
fillDataGrid("SELECT UID, SiteName, DateConnected FROM tblSites ORDER BY DateConnected ASC");
private void fillDataGrid(string query)
{
try
{
_DataAdapter = new SqlDataAdapter(query, _SQLConnection);
_DataTable = new DataTable();
_SQLConnection.Open();
_DataAdapter.Fill(_DataTable);
_SQLConnection.Close();
dataGrid.DataSource = _DataTable;
}
catch
{
}
|
|
|
|
|
How long does it take on management studio ?
|
|
|
|
|
How long does the same query take to run on the database directly? I have a feeling that it could be index related.
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
As with any sql query issue you should test the query in SSMS (SQL Server Management Studio), turn on the Actual Action Plan and run the query. Look for the high cost nodes and deal with those issues.
Never underestimate the power of human stupidity
RAH
|
|
|
|
|
I'm getting the folloiwng error:
A callback was made on a garbage collected delegate of type 'OPC_Library!OPC_Library.OPC_DLL+WriteNotificationDelegate::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.
I m creating an opc server,I have a form opcSrvr & a .cs file called TcpCommServer,
my code is here:
opcSrvr.cs
OPC_DLL.WriteNotificationDelegate writeCallBack;
public static TcpCommServer.ServerCallbackDelegate del;
TcpCommServer _Server;
public opcSrvr()
{
InitializeComponent();
writeCallBack = new OPC_DLL.WriteNotificationDelegate(myWriteCallBack);
del += new Airsprint_OPCServer.TcpCommServer.ServerCallbackDelegate(UpdateUI);
_Server = new Airsprint_OPCServer.TcpCommServer(del);
}
public void UpdateUI(byte[] bytes, Int32 sessionID, int dataChannel)
{
if (this.InvokeRequired)
{
this.Invoke(_Server.ServerCallbackObject, bytes, sessionID, dataChannel);
}
else
{
// the usual stuff
}
}
public void myWriteCallBack(UInt32 hItem, ref Object Value, ref UInt32 ResultCode)
{
ResultCode = 0;
try
{
ResultCode = 0;
if (hItem == TagHandle[0])
{
textBox1.Text = Convert.ToString (Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[0], textBox1.Text, 192);
}
if (hItem == TagHandle[1])
{
textBox2.Text = Convert.ToString(Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[1], textBox2.Text, 192);
}
if (hItem == TagHandle[2])
{
textBox3.Text = Convert.ToString(Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[2], textBox3.Text, 192);
}
if (hItem == TagHandle[3])
{
textBox4.Text = Convert.ToString(Value);
OPC_DLL.UpdateTag.UpdateTag(TagHandle[3], textBox4.Text, 192);
}
}
catch(Exception ex)
{
}
}
private void opcSrvr_Load(object sender, EventArgs e)
{
OPC_DLL.InitWTOPCsvr("{638A1D6E-D7CD-45F4-98E7-ADEB72218DA3}", 1000);
OPC_DLL.EnableWriteNotification(myWriteCallBack, true);
TagHandle[0] = OPC_DLL.CreateTag("Tag.1", textBox1.Text, 192, true);
TagHandle[1] = OPC_DLL.CreateTag("Tag.2", textBox2.Text, 192, true);
TagHandle[2] = OPC_DLL.CreateTag("Tag.3", textBox3.Text, 192, true);
TagHandle[3] = OPC_DLL.CreateTag("Tag.4", textBox4.Text, 192, true);
}
opc.dll is the file which contain all required dll's. its a multithreading programming.can you tell me how to fix this error? am i doing any mistake in initialization? plz help me!!!
|
|
|
|
|
Does this happen when the OPC server is closed, or the application exits? You should properly implement IDisposable on your OPC type so that you can release the event handlers correctly. This requires you to implement a Dispose() method where you can release the server callback delegates.
What is probably happening is that the server isn't referenced anymore so the garbage collector picks it up and collects it, but since the OPC server still has active delegates it tries to call them on a disposed object. You need to release the OPC COM objects and un-initialize the OPC server when the server gets garbage collected.
|
|
|
|
|
It looks like you knew what you were supposed to do but then forgot to do it.
In the constructor you have explicitly created a delegate and assigned it to the field writeCallBack so that it will not be garbage collected. But in the opcSrvr_Load method there is implicit delegate creation in the line
OPC_DLL.EnableWriteNotification(myWriteCallBack, true);
Should that be
OPC_DLL.EnableWriteNotification(this.writeCallBack, true);
Alan.
|
|
|
|
|
Good catch, still needs to implement proper disposal methods though when working with COM objects like OPC servers
|
|
|
|
|
The question is given. Which one's faster? I would think the second one, but I am not sure.
|
|
|
|
|
This SO post may help you[^] - However I doubt if list.First() does anything else than
return list[0];
so list[0] may be marginally faster. As explained in the post, the main difference is the kind of Exception you get when no element is in the list.
cheers,
Marco
|
|
|
|
|
if you can call
var item = list[0]
it's probably faster than calling
var item = list.First()
This is the code of the First Extension
public static TSource First<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
IList<TSource> list = source as IList<TSource>;
if (list != null) {
if (list.Count > 0) return list[0];
}
else {
using (IEnumerator<TSource> e = source.GetEnumerator()) {
if (e.MoveNext()) return e.Current;
}
}
throw Error.NoElements();
}
The First method is a LINQ-Extension and is used for IEnumerable. Not all IEnumberable implementations do support the direct access of elements through an index (As IEnumberable does not have a method implemented for it).
IEnumberable gets implemented by nearly all of the .NET Collections, Lists or Arrays. So you don't have to care if you can access it directly with the index or not.
|
|
|
|
|
Directly accessing the element is faster, if there are elements in the list. However, what about if there are no elements? What happens then? Of course, both cases would result in an exception, which is where the oddity comes into play that is, at this point it's probably faster to call FirstOrDefault if the list can be null. Of course, where things get interesting is the fact that list[0] might contain a value, but it might not be the one that you're interested in, because First is designed to work as a Linq expression, so it can return you the item that is at a certain location based on the results of your Linq query.
|
|
|
|
|
LINQ is quicker to write but not necessarily always faster.
|
|
|
|