Bringing Specific Date Record in MS access using C# - c#

I want to bring a records of commission on specific date. Here is my code;
globalxx = 0;
string month1 = dateTimePicker2.Value.Month.ToString();
string day1 = dateTimePicker2.Value.Day.ToString();
string year1 = dateTimePicker2.Value.Year.ToString();
string s2 = "#" + month1 + "/" + day1 + "/" + year1 + "#";
DataTable results = new DataTable();
using (OleDbConnection conn = new OleDbConnection(xi))
{
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission='" + s2 + "'", conn);
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#DateCommission", s2)
});
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(results);
dataGridView2.DataSource = results;
But the problem is it gives error at
adapter.Fill(results);
saying: "OleDB Excpetion has been handeled Data type mismatch in criteria expression."
I Need help.
My MS Access Schema is:
DateCommission: Date Time
DriverName: TEXT
DriveVehicleNumber: TEXT
CommissionedPrice: NUMBER
I am not got at parameter.
Here is the front end of c#;
Front End

Handle your date as that, and then concatenate a formatted string expression in the SQL:
string textDate = dateTimePicker2.Value.ToString("yyyy'/'MM'/'dd");
string s2 = "#" + textDate + "#";
and then:
OleDbCommand cmd = new OleDbCommand("select * from COMMISSION where DateCommission = " + s2 + "", conn);
Or (preferred) use a parameter of data type DateTime which you pass Value of the datepicker directly.

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.

Conversion between Numeric and Double/Decimal in C#

I'm trying to grab elements from a certain column/Listbox which has the type "numeric" and store them in a List in C#.
datTable = new DataTable();
sqlCmd = new SqlCommand(#
"SELECT DISTINCT [" + form1.getColumnName() + "]
FROM [" + form1.getTableName() + "]", connection);
sqlDatAdapter = new SqlDataAdapter(sqlCmd.CommandText, connection);
sqlDatAdapter.Fill(datTable);
form1.columnStorList.DisplayMember = form1.getColumnName();
form1.columnStorList.ValueMember = "Column1";
form1.costStorList.DataSource = datTable;
List<Decimal> columnElements = new List<Decimal>();
foreach (var selectedItem in form1.columnStorList.SelectedItems)
{
DataRow row = (selectedItem as DataRowView).Row;
columnElements.Add(row.Field<decimal>(form1.getColumnName()));
}
Somehow he don't want to convert it. Double doesn't work at all. For example the value '0,000000' gets displayed as '0'. I tried to convert the elements to Double but then I get '0.0'. Decimal should be the closest to Numeric or am I wrong? How to display it correctly?
I want to use a SELECT Statement (SELECT...FROM...WHERE...=0,000000) to search the value in the database when I highlight it in my Listbox. Since he cuts the values off that specific value won't get found in my database.
The SELECT Statement is:
datTable = new DataTable();
fullStatementColumn = Convert.ToString(columnElements[0]);
String selectStatement = "SELECT [" + form1.colBox.Text + "]
FROM [" + form1.tableNameVal.Text + "]
WHERE convert(varchar(120),[" + form1.getColumnName() + "])='"
+ fullStatementColumn + "'";

C# Mysql select Date(yyyy/mm/dd) from column by month value (12)

I am trying to figure out the way to sum values of certain columns. How do I get Date month value from Date column where all values are in date (yyyy/mm/dd) format?
What I should write in :
WHERE Data = '"?????"' ";
I want to pick up date where month equals 12.
Here is my code :
MySqlConnection cnn = new MySqlConnection(connectionString);
cnn.Open();
string query = "select sum(SUMA) from `nuolatines pajamos` WHERE ID = '" + perdavimo1.id_permetejas.ToString() + "' WHERE Data = '"+ now.Month +"' ";
MySqlCommand createCommand = new MySqlCommand(query, cnn);
var sum = createCommand.ExecuteScalar().ToString();
nl_pajamos.Text = sum.ToString();
DateTime.Parse(stringobject,cultureinfo);
for example
DateTime.Parse("20-01-2014",new CultureInfo("nl-BE

How to write IF SQL statement in C# for retrieving values from database

I have these three columns in UI. In dropdown I have a AllRecords and some other field. I select that AllRecords field and I enter start and end date details.
Now I write a query for that for retrieving the values.
When he select AllRecords, depending upon start and end dates, it have to display OR retrieve the data from database table.
I have written a query if the user will select other values, it looks like this ,
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails where Date between '"
+ DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd")
+ "' and '"
+ DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd")
+ "' and Name ='"
+ DropDownList1.Text.ToString()
+ "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
Now the problem is I have to write query for AllRecords.
try this:
DataTable dt = new DataTable();
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails ";
if ( DropDownList1.Text.ToString() != "AllRecords")
queryStr=queryStr+" where Date between '" + DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd") + "' and '" + DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd") + "'"+" and Name ='" + DropDownList1.Text.ToString() + "'";
SqlDataAdapter s1 = new SqlDataAdapter(queryStr, conn);
s1.Fill(dt);
Only a small change in your query
You have to append and Name ='" + DropDownList1.Text.ToString() to the query only if its not AllRecords
Be care about SQL Injection. Use SQLParameter like this:
DataTable dt = new DataTable();
SqlDataAdapter s1 = new SqlDataAdapter();
s1.SelectCommand.Connection = conn;
string queryStr = "SELECT Day,Date,Name,Task,Hours from TaskManualDetails WHERE Date BETWEEN #StartDate AND #EndDate";
s1.SelectCommand.Parameters.AddWithValue("StartDate", DateTime.Parse(txtStartDate.Text).ToString("yyyy-MM-dd"));
s1.SelectCommand.Parameters.AddWithValue("EndDate", DateTime.Parse(txtEndDate.Text).ToString("yyyy-MM-dd"));
if (DropDownList1.Text.ToString() != "AllRecords")
{
queryStr = queryStr + " AND Name = #Name";
s1.SelectCommand.Parameters.AddWithValue("Name", DropDownList1.Text.ToString());
}
s1.SelectCommand.CommandText = queryStr;
s1.Fill(dt);

how to insert a date from textbox to database

please help me to insert a date from a text box in dd-mm-yyyy format to sql server.
my code is as follows:-
int prio = Convert.ToInt32(Priority.Text);
string stdate = planstart.Text;
string endate= planend.Text;
string actst = actualstart.Text;
string acten = actualend.Text;
SqlConnection myconnection = new SqlConnection(constring);
SqlCommand mycommand = new SqlCommand();
DataSet mydataset = new DataSet();
SqlDataAdapter mydataadapter = new SqlDataAdapter();
myconnection.Open();
mycommand.Connection = myconnection;
mycommand.CommandText = " insert into project_status.dbo.Project_Status_Report values('" + projectcode.Text + "','" + projectname.Text + "',(select P_Code from project_status.dbo.Project_Type where Project_Type = '" + projecttype.Text + "')," + prio + ",'" + stdate + "','" + endate + "','" + actst + "','" + acten + "','" + currentstatus.Text + "','" + remark.Text + "','no');";
mycommand.CommandType = CommandType.Text;
mycommand.ExecuteNonQuery();
and it is throwing an exception saying:-
Conversion failed when converting date and/or time from character string.
You need to convert data according to you sql server formate that way you can resolve issue ..
Try
String UrDate = "27/12/2011";
System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
dateInfo.ShortDatePattern = "dd/MM/yyyy";
DateTime validDate= Convert.ToDateTime(toDate, dateInfo);
or
Format String For Dates
// String to DateTime
String MyString;
MyString = "1999-09-01 21:34 PM";
//MyString = "1999-09-01 21:34 p.m."; //Depends on your regional settings
DateTime MyDateTime;
MyDateTime = new DateTime();
MyDateTime = DateTime.ParseExact(MyString, "yyyy-MM-dd HH:mm tt",
null);
Make use of Paramerize query to avoid SQL INJECTION...make code less error pron
Walkthrough: Displaying Data in a Windows Form Using a Parameterized Query
Just a word of caution - you need to sanitize that query to prevent SQL injection attacks. Consider using parameterised queries. Read up about it, it's not really the scope of this answer.
You should create strongly typed DateTime objects first and then format them the way you need to insert. Consider the following modification to your code:
string stdate = DateTime.Parse(planstart.Text).ToString();
string endate = DateTime.Parse(planend.Text).ToString();
string actst = DateTime.Parse(actualstart.Text).ToString();
string acten = DateTime.Parse(actualend.Text).ToString();
EDIT
I removed the string parameter from the ToString() so you can get a valid DateTime string that's usable by SQL Server.
con.Open();
string query = "insert_demo";
/* date fromat Stored*/
TextBox2.Text = DateTime.Now.ToLongDateString();
SqlCommand com = new SqlCommand(query, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Name", TextBox1.Text.ToString());
com.Parameters.AddWithValue("#Date", TextBox2.Text.ToString());
com.ExecuteNonQuery();

Categories