Parameterized Queries not working - c#

I had the following implementation of filling a DataTable with SQL:
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
string sSQL = #"SELECT LogID, Severity, Title
FROM dbo.Log
WHERE UPPER(LogID) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Severity) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Title) LIKE '%" + searchPhrase.ToUpper() + #"%' ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + (Convert.ToInt32(current) - 1).ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
}
catch { }
This works nicely but I've realized that this is dangerous due to SQL Injection. So I've tried to solve that danger using parameterized queries like this:
var con = new SqlConnection();
var cmd = new SqlCommand();
var dt = new DataTable();
cmd.Parameters.Add(new ObjectParameter("#searchPhrase", searchPhrase.ToUpper()));
cmd.Parameters.Add(new ObjectParameter("#orderBy", orderBy));
cmd.Parameters.Add(new ObjectParameter("#orderFrom", orderFrom));
cmd.Parameters.Add(new ObjectParameter("#current", current));
cmd.Parameters.Add(new ObjectParameter("#rowCount", rowCount));
string sSQL = #"SELECT LogID, Severity, Title
FROM dbo.Log
WHERE UPPER(LogID) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Severity) LIKE '%" + searchPhrase.ToUpper() + #"%' OR UPPER(Title) LIKE '%" + searchPhrase.ToUpper() + #"%' ORDER BY " + orderBy + " " + orderFrom + #"
OFFSET ((" + (Convert.ToInt32(current) - 1).ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
try
{
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
{
using (var command = new SqlCommand(sSQL, connection))
{
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}
}
}
catch { }
Unfortunately now my data table doesn't fill. What am I doing wrong?

You are using multiple command and connection references, not sure if thats a copy/paste problem or your actual code is like that. In the second case it will not even compile.
Reference the parameters directly in your query, see below. Sql Server uses named parameters so the same parameter can be reused in multiple locations.
Desc/Asc cannot be used as a parameter. You should double check the value though or use an enum and pass that (recommended).
The same is true of the numeric values for rowcount, pass those in as numbers or check their values using a TryParse to ensure it is numeric and not malicious code.
The default install options for Sql Server is for a case insensitive coalition. This means you do not have to UPPER a string to do a comparison. If you do have a case sensitive install then do not change this, otherwise remove all calls to UPPER when doing comparisons.
Finally you well never know why your code is not working if you surround your code in try/catch and have an empty catch block. Your code will fail silently and you will be left scratching your head. Do not do this anywhere in your code, it is bad practice!! Either catch the exception and handle it (do something so code can recover) OR log it and rethrow using throw; OR do not catch it at all. I chose the later and removed it.
Code
var currentNum = Convert.ToInt32(current) - 1;
var temp = 0;
if(!"desc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase) && !"asc".Equals(orderFrom, StringComparison.OrdinalIgnoreCase))
throw new ArgumentException("orderFrom is not a valid value");
if(!int.TryParse(rowCount, out temp))
throw new ArgumentException("Rowcount is not a valid number");
var dt = new DataTable();
string sSQL = #"SELECT LogID, Severity, Title
FROM dbo.Log
WHERE UPPER(LogID) LIKE #searchPhrase
OR UPPER(Severity) LIKE #searchPhrase
OR UPPER(Title) LIKE #searchPhrase
ORDER BY #orderBy " + orderFrom + "
OFFSET ((" + currentNum.ToString() + ") * " + rowCount + #") ROWS
FETCH NEXT " + rowCount + " ROWS ONLY;";
using (var connection = THF.Models.SQLConnectionManager.GetConnection())
using (var command = new SqlCommand(sSQL, connection))
{
cmd.Parameters.Add(new SqlParameter("#searchPhrase", "%" + searchPhrase.ToUpper() + "%"));
cmd.Parameters.Add(new SqlParameter("#orderBy", orderBy));
connection.Open();
command.CommandTimeout = 0;
var da = new SqlDataAdapter(command);
da.Fill(dt);
}

Here is a simple example of how this should be done.
con.Open();
SqlCommand cmd = new SqlCommand(#"insert into tbl_insert values(#name,#email,#add)", con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();

Related

objDataReader is Null - ASP.NET C#

I am quite new to ASP.NET and C#, so I still do not have much of an idea as to how things work. I basically get an error when I run my program and create a maintenance task. My code is shown right below:
private DataTable getMaintenance()
{
DataTable maintenance_dt = new DataTable();
maintenance_dt.Columns.Add("maintenance_ID");
maintenance_dt.Columns.Add("DAILY_MAINTENANCE");
maintenance_dt.Columns.Add("ADMIN_COMMENT");
string SQLstr = "SELECT MAINTENANCE_ID,DAILY_MAINTENANCE,ADMIN_COMMENT FROM " + maintenance_table + " where " + key + " like " + value + " order by MAINTENANCE_ID ";
using (DataTableReader objDataReader = OS.OSFunctions.executeSQLQuery(SQLstr))
{
while (objDataReader.Read())
{
DataRow mItem = maintenance_dt.NewRow();
mItem[0] = objDataReader["MAINTENANCE_ID"].ToString();
mItem[1] = objDataReader["DAILY_MAINTENANCE"].ToString();
if (objDataReader["ADMIN_COMMENT"] != DBNull.Value)
{
mItem[2] = objDataReader["ADMIN_COMMENT"].ToString();
}
else
{
mItem[2] = "";
}
maintenance_dt.Rows.Add(mItem);
}
}
return maintenance_dt;
}
The error I get from running this states
Object reference not set to an instance of an object. objDataReader was null
This occurs when I attempt to create a maintenance task. The code for that is also below right here:
protected void createMaintenance_Click(object sender, System.EventArgs e)
{
string SQLstr;
if (txtMaintenanceName.Text.Length > 0)
{
if (maintenance_table == "ACTIVE_DAILYMAINTENANCE")
{
SQLstr = "SELECT TOP(1) MAINTENANCE_ID FROM ACTIVE_DAILYMAINTENANCE WHERE SCHEDULE_DATE = " + value + " ORDER BY MAINTENANCE_ID desc";
using (DataTableReader objDataReader = OS.OSFunctions.executeSQLQuery(SQLstr))
{
if (objDataReader.Read())
{
int id = Convert.ToInt32(objDataReader["Maintenance_ID"]) + 1;
SQLstr = "insert into " + maintenance_table + " (maintenance_id, DAILY_MAINTENANCE, " + key + ", ADMIN_COMMENT) values ('" + id + "',"
+ " '" + txtMaintenanceName.Text + "'," + value + ",'" + txtAdminMaintenanceComment.Text + "')";
OS.OSFunctions.executeSQLNonQuery(SQLstr);
}
}
}
else
{
SQLstr = "insert into " + maintenance_table + "(DAILY_MAINTENANCE, " + key + ", ADMIN_COMMENT) values ('" + txtMaintenanceName.Text + "'," + value + ",'" + txtAdminMaintenanceComment.Text + "')";
OS.OSFunctions.executeSQLNonQuery(SQLstr);
}
}
Again, it is the getMaintenance() method giving me the error. This also isn't all my code, I do call the getMaintenance() function sometime later in the code for CreateMaintenance. Any help would be greatly appreciated.
EDIT: CODE TRYING OUT DATA SET
private DataSet getMaintenance()
{
DataSet maintenance_ds = new DataSet();
string SQLstr= "SELECT MAINTENANCE_ID,DAILY_MAINTENANCE,ADMIN_COMMENT FROM " + maintenance_table + " where " + key + " like " + value + " order by MAINTENANCE_ID ";
using(SqlConnection connection=new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnectionString"].ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = new SqlCommand(SQLstr, connection);
adapter.Fill(maintenance_ds);
return maintenance_ds;
}
}
So, you execute
DataTableReader objDataReader = OS.OSFunctions.executeSQLQuery(SQLstr)
in your using. SQLstr is
"SELECT MAINTENANCE_ID,DAILY_MAINTENANCE,ADMIN_COMMENT FROM " + maintenance_table + " where " + key + " like " + value + " order by MAINTENANCE_ID ";
You will need to use a debugger and jump to this line just before the error is thrown. First of all, you will need to find out what maintenance_table, key and value is. Try finding out what the generated query is and run it in your RDBMS, I think it will most likely return a null for some reason.
It is possible that you are just missing a wildcard character of % being wrapped around value if you have the intention to have a "contains" rather than an "equals" check.
Anyway, in order to detect what the error is you will need to find out what is being generated and why your query results in a null. Once you know what the problem is, you will also know what you need to fix, which largely simplifies the problem.
Since you do not use a parameterized query, I have to mention that if any of the dynamic values you concatenate to the query may come from untrusted sources, such as user input, then your query is vulnerable to SQL injection and you will need to protect your project against this potential exploit.
You do realize that you can send the sql to a datatable, and the columns and the data table is created for you.
so, use this code to get/return a data table.
It not clear if you "else" is to update a existing row, or insert a new one, but the code can look somthing like this:
protected void createMaintenance_Click(object sender, System.EventArgs e)
{
DateTime value = DateTime.Today;
string maintenance_table = "";
string SQLstr = "";
string key = "";
if (txtMaintenanceName.Text.Length > 0)
{
if (maintenance_table == "ACTIVE_DAILYMAINTENANCE")
{
// add new row
int id = NextMaintID(value);
string strSQL = #"SELECT * FROM " + maintenance_table + " WHERE Maintenance_ID = 0";
DataTable rstSched = MyRst(strSQL);
DataRow MyNewRow = rstSched.NewRow();
MyNewRow["maintenance_id"] = id;
MyNewRow["DAILY_MAINTENANCE"] = txtMaintenanceName.Text;
MyNewRow["ADMIN_COMMENT"] = txtAdminMaintenanceComment.Text;
rstSched.Rows.Add(MyNewRow);
MyUpdate(rstSched, strSQL);
}
}
else
{
// update (or add to daily?????
string strSQL = #"SELECT * FROM " + maintenance_table + " WHERE Maintenance_ID = " + key;
DataTable rstSched = MyRst(strSQL);
DataRow MyRow = rstSched.Rows[0];
MyRow["DAILY_MAINTENANCE"] = txtMaintenanceName.Text;
MyRow["ADMIN_COMMENT"] = txtAdminMaintenanceComment.Text;
MyUpdate(rstSched, strSQL);
}
}
So, I only need a few helper routines - (make them global in a static class - you can then use it everywhere - saves boatloads of code.
so these were used:
public DataTable MyRst(string strSQL)
{
// return data table based on sql
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
public DataTable MyRstP(SqlCommand cmdSQL)
{
// return data table based on sql command (for parmaters)
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (cmdSQL)
{
cmdSQL.Connection = conn;
conn.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
void MyUpdate(DataTable rstData, string strSQL)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
da.Update(rstData);
}
}
}
and of course this:
int NextMaintID (DateTime value)
{
int result = 0;
string SQLstr = #"SELECT TOP(1) MAINTENANCE_ID FROM ACTIVE_DAILYMAINTENANCE
WHERE SCHEDULE_DATE = #scDate ORDER BY MAINTENANCE_ID desc";
SqlCommand cmdSQL = new SqlCommand(SQLstr);
cmdSQL.Parameters.Add("#scDate", SqlDbType.Date).Value = value;
DataTable rstNextID = MyRstP(cmdSQL);
result = ((int)rstNextID.Rows[0]["Maintenance_ID"]) + 1;
return result;
}
So, how do you eat a elephant?
Answer: One bite at a time!!!
So, break out just a "few" helper routines that allows data operations against a data table object. That update command will work with edits, adds to rows, and even delete row method of a single row. All such updates can be thus be done with ONE simple update command.

Syntax Error Ocurring on the Data Reader

try
{
int i = 0;
using (SqlConnection sqlCon = new SqlConnection(Form1.connectionString))
{
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
// MessageBox.Show(commandString);
SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);
sqlCon.Open();
SqlDataReader dr = sqlCmd.ExecuteReader();
i = 1;
if (i == 0)
{
MessageBox.Show("Error in Logging In!", "Error");
}
MessageBox.Show("Successfully Logged In");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I'm making a LoginForm for a Project.I have created a table which shows the LoginDetails(Account,ID,LoginTime,LogoutTime).But when I run the Program,it doesn't runs successfully.I face an error which is in Pic-2.When I remove sql 'data reader',the program runs without displaying the error.
When you concatenate a null it basically adds nothing to the string, so this code:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID.Text + "," + null + ", SYSDATETIME()" + ");";
results of this string, and as you can see it has an extra comma, that causes the exception:
"INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('acc',textbxID,, SYSDATETIME());"
If you want to add NULL to the query it has to be a string, so do this instead:
string commandString = "INSERT INTO Logindetail (Account,ID,Logint,Logoutt) values ('" + acc + "'," + textbxID + ", NULL , SYSDATETIME()" + ");";
And you are using ExecuteReader instead of ExecuteNonQuery. You cannot use ExecuteReader for inserting rows to the DB.
Also, as someone mentioned in the other answer, you better do it with parametes to avoid SQL Injections.

There is already an open Data Reader associated with this Command which must be closed first Exception

I am getting an exception called There is already an open Data Reader Associated with this command which must be closed first, I tried to look up solution on Google I tried using MARS=true in connection string and also kept everything inside USING but it didn't solved the problem.
i get an Exception in line
cm.ExecuteNonQuery();
public void UpdateActionSchedule(string actionScheduleKey, string note, string PEOPLE_CODE_ID)
{
using (SqlConnection con = new SqlConnection("server=123; database=abc; user id=qwe; password=qwe;"))
{
con.Open();
if (note == "" || note == null)
{
string UPDATE_COMPLETE = String.Format("UPDATE ACTIONSCHEDULE SET EXECUTION_DATE = '" + DateTime.Now + "', COMPLETED = 'Y', REVISION_OPID='WFLOW' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
SqlCommand cd = new SqlCommand(UPDATE_COMPLETE, con);
cd.ExecuteNonQuery();
cd.Dispose();
}
else
{
string oriNote = "";
string GET_NOTE = String.Format("SELECT NOTE FROM ACTIONSCHEDULE WHERE people_org_code_id='{0}' and UNIQUE_KEY='{1}'", PEOPLE_CODE_ID, actionScheduleKey);
using (SqlCommand cmd = new SqlCommand(GET_NOTE, con))
{
// SqlDataReader dr = cmd.ExecuteReader();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
oriNote = dr["NOTE"].ToString();
}
note = oriNote + " " + note;
}
//string UPDATE = String.Format("UPDATE ACTIONSCHEDULE SET Note = '" + note + "' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
//SqlCommand cm = new SqlCommand(UPDATE, con);
//cm.ExecuteNonQuery();
//cm.Dispose();
string UPDATE_COMPLETE = String.Format("UPDATE ACTIONSCHEDULE SET EXECUTION_DATE = '" + DateTime.Now + "',Note = '" + note + "', COMPLETED = 'Y', REVISION_OPID='WFLOW' where UNIQUE_KEY = '" + actionScheduleKey + "' and people_org_code_id='" + PEOPLE_CODE_ID + "'");
SqlCommand cmw = new SqlCommand(UPDATE_COMPLETE, con);
cmw.ExecuteNonQuery();
cmw.Dispose();
}
}
}
}
}
In the second half of the code, you have a loop over cmd / dr, and inside that loop, you use cmw with ExecuteNonQuery. That means you're trying to execute two commands at once. Since you've already completed the loop: just move that code outside the using on the dr.
However, it looks like you could also do all of this in a single round trip with better SQL.

C# InsertCommand Queries

I have an access database connected to my project and want to save back edits. The edits only seem to save when existing values are being modified. When I insert a row or delete a row using my binding navigator, It does not update my database. I have tried many queries:
try
{
query = string.Format("SELECT * FROM {0}", Text);
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.InsertCommand = new OleDbCommand(query, conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
OleDbCommandBuilder builder = new OleDbCommandBuilder(adapter);
adapter.Update(Account);
Console.WriteLine("Saved");
}
catch (Exception ex)
{
Console.WriteLine(ex.InnerException + ":" + ex.Message);
}
In a DataGridView.RowAdded event I added the following code:
try
{
string AccNum = accountGridView.Rows[e.RowIndex].Cells[0].Value.ToString();
string lName = accountGridView.Rows[e.RowIndex].Cells[1].Value.ToString();
string fName = accountGridView.Rows[e.RowIndex].Cells[2].Value.ToString();
string balance = accountGridView.Rows[e.RowIndex].Cells[3].Value.ToString();
adapter.InsertCommand = new OleDbCommand("INSERT INTO " + Text + " VALUES ("
+ AccNum + ", " + lName + ", " + fName + ", " + balance + ")", conn);
adapter.SelectCommand = new OleDbCommand(query, conn);
adapter.DeleteCommand = new OleDbCommand(query, conn);
adapter.Update(Account);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + ":" + ex.InnerException);
}
In my RowAdded Event, it gives me an error and in my regular save event, everything works just fine besides the Insert and Delete Commands. Does anyone know the queries I can use to make this work?
I solved my problem by removing my RowsAdded event and all the InsertCommands and DeleteCommands. I think the problem was I was overriding the default InsertCommands and DeleteCommands with bad SqlCode.

how to insert date(long format) into access database using datetimepicker in c# ? (error is in date part only)

Error image is here
the error is in query line , its shows syntax error
try
{
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
command.CommandText = "insert into client_table(CLIENT, DATE,BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #" + dat.ToLongDateString() + "# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
this.Hide();
employee_form f1 = new employee_form("");
f1.ShowDialog();
}
thank you in advance
In Access, dates are delimited by #, not '. Also, Access does not recognize the long date format. But dates are not stored in any format so no worries, change it to:
... + "', #" + dat.ToString() + "# ...etc.
Although if you do not parameterize your query serious damage or data exposure can be done through SQL Injection because someone could type in a SQL statement into one of those textboxes that you are implicitly trusting.
Working example:
class Program
{
static void Main(string[] args)
{
System.Data.OleDb.OleDbConnectionStringBuilder bldr = new System.Data.OleDb.OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new System.Data.OleDb.OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#" + DateTime.Now.ToString() + "#)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
}
Update
However, you want to do something more like this which uses Parameters to protect against SQL Injection which is extremely easy to exploit so do not think that you don't really need to worry about it:
static void Main(string[] args)
{
OleDbConnectionStringBuilder bldr = new OleDbConnectionStringBuilder();
bldr.DataSource = #"C:\Users\tekhe\Documents\Database2.mdb";
bldr.Provider = "Microsoft.Jet.OLEDB.4.0";
using (System.Data.OleDb.OleDbConnection cnxn = new OleDbConnection(bldr.ConnectionString))
{
cnxn.Open();
Console.WriteLine("open");
using (System.Data.OleDb.OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = cnxn;
cmd.CommandType = System.Data.CommandType.Text;
OleDbParameter dobParam = new OleDbParameter("#dob", OleDbType.Date);
dobParam.Value = DateTime.Now;
cmd.Parameters.Add(dobParam);
cmd.CommandText = "INSERT INTO [Table1] ([Dob]) VALUES(#dob)";
cmd.ExecuteNonQuery();
}
}
Console.ReadKey();
}
//code to write date in the access table.
string zero = "0";
DateTime dat = this.dateTimePicker1.Value.Date;
//MessageBox.Show(dat.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
//command.CommandText = "insert into client_table(DATEE) values( '"dat.ToShortDateString()+"')";
command.CommandText = "insert into client_table (CLIENT, DATEE, BILL_AMOUNT, PAID_AMOUNT, BALANCE, CONTACT, ADDRESS )VALUES ('" + txt_client.Text + "', #"+dat.ToShortDateString()+"# ,'" + zero + "','" + zero + "','" + zero + "','" + txt_contact.Text + "','" + txt_address.Text + "')";
command.ExecuteNonQuery();
connection1.Close();
MessageBox.Show("New Client Registration done Successfully.");
connection1.Dispose();
//New code for receiving the date between two range of dates
try
{
DateTime dat = this.dateTimePicker1.Value.Date;
DateTime dat2 = this.dateTimePicker2.Value.Date;
// MessageBox.Show(dat.ToShortDateString() + " " + dat2.ToShortDateString());
connection1.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection1;
string query;
query = "select * from client_table Where DATEE Between #" + dat.ToLongDateString() +"# and #" + dat2.ToLongDateString() + "# ";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection1.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
Thank you all of you for the support.

Categories