I am trying to make c# program, where I have to make a database report to be previewed at the datagridview. Data will be selected using the datetimepicker. I have written the code, it works but then if the date selected is of different months. No records appear
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
please help me check my code and tell me what might be wrong or missing.
Use profiler to check the query that hits the DB. I suspect it's a date formatting issue.
Maybe this question can help you with logging the queries that hit the database:
Hope this helps:
Select * from [Table] where StartDate between '06/13/2016' and '10/13/2016'
The above query fetches records between months 06 and 10. Make sure that string in the data variable is in the above format. Also the column type in the database is date.
Check and remove special characters, if any.
Mark this as answer if you find this useful.
Try this for your select query. I have changed one of your select variable because it ambiguous for the Date datatype.
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
//string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
//Changed query for getting data from DB according to the date
string data = "SELECT CreatedDate, Process, Actual, Target FROM database WHERE DATE_FORMAT(CreatedDate,'%Y-%m-%d') BETWEEN '"+this.fromDatePicker.Value.ToString("yyyy-MM-dd")+"' AND '"+this.toDatePicker.Value.ToString("yyyy-MM-dd")+"' order by CreatedDate desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
Related
I have been really struggling to sort this data by date and time. As you can see, I have got this data. In addition, the data table is not taking the same space as the dataGridView space. How do I resolve that problem?
I am trying to sort out this data in c#. I have generated the above table by writing the below code:
private void ViewAppointment_Load(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("server=localhost;port=****;username=root;password=****;database=appointment; pooling = false; convert zero datetime = True");
string Query = "SELECT * FROM `appointmentdetails`";
MySqlCommand myCommand = new MySqlCommand(Query, connection);
MySqlDataAdapter myAdapater = new MySqlDataAdapter();
myAdapater.SelectCommand = myCommand;
DataTable dTable = new DataTable();
myAdapater.Fill(dTable);
dataGridView1.DataSource = dTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Thanks for your time
You can either sort directly on the DataGrid:
dataGridView1.Sort(dataGridView1.Columns["Date"], ListSortDirection.Ascending);
Or get the data sorted from sql:
string Query = "SELECT * FROM `appointmentdetails` order by Date";
You need to add your sorting to the Query
private void ViewAppointment_Load(object sender, EventArgs e)
{
try
{
MySqlConnection connection = new MySqlConnection("server=localhost;port=****;username=root;password=****;database=appointment; pooling = false; convert zero datetime = True");
string Query = "SELECT * FROM `appointmentdetails ORDER BY date DESC`";
MySqlCommand myCommand = new MySqlCommand(Query, connection);
MySqlDataAdapter myAdapater = new MySqlDataAdapter();
myAdapater.SelectCommand = myCommand;
DataTable dTable = new DataTable();
myAdapater.Fill(dTable);
dataGridView1.DataSource = dTable;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am developing an Attendance Monitoring System and I need the employee form to select data from ms access with a specific date when it runs, I need it to show different data daily. for example 10 persons timed in just lately this day, it will select that but on the next day it will fetch another batch of data
here's my code
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
DateTime dateTime = dateTimePicker1.Value;
string query = "SELECT FROM TimeinTimeout WHERE InDate=" + String.Format("{0:# MM/dd/yy #}", dateTime);
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Update();
dataGridView1.Refresh();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This allows the user to select a date of all the TimeinTimeout data for a specific day
private void button1_Click(object sender, EventArgs e)
{
SqlDataAdapter sdf = new SqlDataAdapter("select * from TimeinTimeout where date'" + dateTimePicker1.Value.ToString() + "'", constring); ;
DataTable sd = new DataTable();
sdf.Fill(sd);
dataGridView1.DataSource = sd;
}
This code is placed in the button. and when i click it to update the data, a messagebox error appears saying "fatal error encountered during command execution".
Your answers would be a great help. Thank you
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd;
try
{
connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText = "UPDATE student_offense SET TYPE=#TYPE,DATE_HAPPENED=#DH,DESCRIPTION=#DESC,SANCTION=#SANC" +
"Where STUDENT_NO = #STUDENT_NO And DESCRIPTION=#DESC And SANCTION=#SANC And DATE_HAPPENED=#DH";
cmd.Parameters.AddWithValue("#TYPE", offense_combo.Text);
cmd.Parameters.AddWithValue("#DH", date_hapen.Text);
cmd.Parameters.AddWithValue("#DESC", description_txt.Text);
cmd.Parameters.AddWithValue("#SANC", sanction_txt.Text);
cmd.Parameters.AddWithValue("#STUDENT_NO", studentNo_txt.Text);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
MessageBox.Show("updated");
//refresh
cmd.CommandText = "SELECT student_info.Student_no,student_info.Lastname,student_info.Firstname,student_offense.Type,student_offense.Description,student_offense.Date_Happened,student_offense.Sanction,student_offense.Date_Recorded from student_info,student_offense where student_info.student_no = student_offense.student_no";
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
dbdataset = new DataTable();
sda.Fill(dbdataset);
bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
student_no_valid.Visible = false;
stud_no_error.Visible = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
listBox1.Items.Clear();
description_txt.Text = "";
studentNo_txt.Text = "";
offense_combo.Text = "";
current_date();
sanction_txt.Text = "";
You are missing space between Parameter #SANC and Where .
Try This:
cmd.CommandText = "UPDATE student_offense SET TYPE=#TYPE,DATE_HAPPENED=#DH,
DESCRIPTION=#DESC,SANCTION=#SANC" + " Where STUDENT_NO = #STUDENT_NO And
DESCRIPTION=#DESC And SANCTION=#SANC And DATE_HAPPENED=#DH";
Suggestion : if your DATE_HAPPENED column type is Date in your table,then You need to send the proper Date format.
Try This: Assuming user enters Date in dd-MM-yyyy format.
DateTime dt = DateTime.ParseExact(date_hapen.Text,"dd-MM-yyyy",
CutureInfo.InvariantCulture);
Now while assigning the DATE_HAPPENED value provide the following format
cmd.Parameters.AddWithValue("#DH",dt.ToString("yyyy-MM-dd"));
Probably this happened at cmd.ExecuteNonQuery(); or in the subsequent query. You can verify this by single-stepping through after a breakpoint. There is probably an error in the SQL. You can find this by looking at the internal error, or by trying the query on MySQL Workbench. Check to see that all of the parameters match table columns, and all the data types match.
Incidentally, there is no need to assign SANCTION and DATE_HAPPENED in the update statement since you required them to be equal in the WHERE.
i have to search data from the text box in datagrid using c#
My code is
private void button_Search_Click(object sender, EventArgs e)
{
sqlcon.Open();
//DataSet ds15 = new DataSet();
DataTable dt= new DataTable();
SqlDataAdapter adpt = new SqlDataAdapter("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text);
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
Getting error Arguement exception was unhandled
I want to search through combo box
there is no constructor match your parameters on SqlDataAdapter
SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from TableName where Field like '%{0}%'",
comboBox_Search.Text), sqlcon);
Query every time to the database is not a preferable approach. Instead take a BindingSource object and fill the source once. Then use BindingSource.Filter property to get relevant result set and bind the result set to grid.
Have a look at this and and this link.
Also, to fix your issue you can try like this:
....
sqlcon.Open();
string query = string.Format("Select ColumName from TableName where Field like '%{0}%'", comboBox_Search.Text);
SqlCommand cm = new SqlCommand(query, sqlcon);
SqlDataAdapter adpt = new SqlDataAdapter(cmd);
adpt.Fill(dt);//datatable to catch the fields from the database
dataGridView1.DataSource = dt;
....
How does the SqlDataAdapter know where to get the result from?
You are not initializing the constructor for your SqlDataAdapter properly. The first argument is the full select statement and the second argument is your connection string.
SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from atm_status where Table like '%{0}%'", comboBox_Search.Text), sqlcon);
private void txt_Searchque_TextChanged(object sender, EventArgs e)
{
string connector_string = "datasource = localhost;port=3306;username=root;password=;";
MySqlConnection sqlcon = new MySqlConnection(connector_string);
sqlcon.Open();
string query = string.Format("Select * from oep.quiz where que like '%{0}%'", txt_Searchque.Text);
MySqlCommand cmd = new MySqlCommand(query, sqlcon);
MySqlDataAdapter adpt = new MySqlDataAdapter(cmd);
DataTable dt = new DataTable();
adpt.Fill(dt);
dataGridView1.DataSource = dt;
}
I'm developing a library system for my project. My adviser ask me to compute a fine for overdue books. I have 3 textboxes one for student id, book title and isbn, and I also have two datetime pickers; one is for date and one for due date. I want a create a command that will compute a fine if the borrower didn't return the book on duedate and will input the fine in my table 'Borrowbook' column 'Penalty'.
This is my code:
string constring = ("Data Source=.\\SQLEXPRESS;Integrated Security=True");
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Student ID], ISBN, Title, Date, [Due Date], Penalty FROM Borrowbook;", con);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable Records = new DataTable();
sda.Fill(Records);
BindingSource bsource = new BindingSource();
bsource.DataSource = Records;
dataGridView1.DataSource = bsource;
sda.Update(Records);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (dateTimePicker2.Value < DateTime.Now)
{
cmd.CommandText = "INSERT INTO Borrowbook (Penalty) VALUES (#Penalty)";
SqlParameter p1 = new SqlParameter("#Penalty", SqlDbType.Date);
p1.Value = 50;
cmd.Parameters.Add(p1);
cmd.ExecuteNonQuery();
}
}
This code is not working but it runs properly and didn't have any errors. But I think this is the idea for my code. I put this code in the button where also my datagridview will show my data.
You haven't executed your query.
You need:
cmd.ExecuteNonQuery();
You will also need a SqlConnection object that points to the correct SQL Server database.
As an additional note, your database schema looks a bit fuzzy, how would you know what person incurred the penalty? You haven't inserted any other identifier, just the penalty amount.