Hi Sameera,
Looks like you are from SL. I am too :)
There are couple of problems in your code.
1. Nishant pointed out one in the while loop
2. You should include the following line of code in the
SqlCommand()
method after the 2nd line.
comdata.CommandType = CommandType.Text;
3. In
OldDbCommand
there are 2 main methods you can use to execute SQL.
-
ExecuteReader()
: This method is used to execute SELECT queries
-
ExecuteNonQuery()
: This method is used to execute DELETE, UPDATE, INSERT like queries
So in your
SqlCommand()
method you need to remove the 4th line. Since what you are trying to execute is only a SELECT sql. If you want to execute a INSERT or DELETE or UPDATE, you need to create another method for it and use the
ExecuteNonQuery()
method in it.
Try these things out and get back to us with any exception details or messages that you get and the line numbers in which the exceptions occur. The more information we have, easier and faster we can help you.
Hope this helps, regards
Pasan.
P.S. : I was just about to go to sleep, but I wanted to help you understand how to write this code easily and more robustly. So I re-wrote your logic, to show how I would write it, in a small application. Take a look at this code and try to understand it and let me know of any problems. On top of it all, I hope I did not confuse you :)
using (OleDbConnection connection = new OleDbConnection())
{
try
{
connection.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=Employee Details.mdb";
using (OleDbCommand command = connection.CreateCommand())
{
command.CommandText = "select count(EmployeeN0) from Employee where EmployeeN0 = @EmployeeNo";
command.CommandType = CommandType.Text;
OleDbParameter employeeNumberParameter = command.CreateParameter();
employeeNumberParameter.ParameterName = "@EmployeeNo";
employeeNumberParameter.Value = txtnum.Text;
command.Parameters.Add(employeeNumberParameter);
connection.Open();
reader = command.ExecuteReader();
reader.Read();
int c = reader.GetInt32(0);
MessageBox.Show(c.ToString());
int d = (int)command.ExecuteScalar();
MessageBox.Show(c.ToString());
}
}
finally
{
if (connection.State == ConnectionState.Open)
try { connection.Close(); }
catch { }
}
}
Cheers :D