Search for all days of a week using dateTimePicker - c#

I want to retrieve all days of a week, selecting any day of that given week.
Example: Wanna retrieve 31/07/2016 (dd/MM/yyyy) to 06/08/2016 (dd/MM/yyyy)
Ocurrences by selecting any day of the presented week.
Is it possible?
My current code:
private void AutoLoadCalendar()
{
string constringF = #"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
string QueryF = "select * from Funcionarios where (status = N'Ativo') and datepart(year, datafimcontrato) = #ano and datepart(month, datafimcontrato) = #mes ";
SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
cmdDataBaseF.Parameters.Add("#mes", SqlDbType.Int).Value = Convert.ToInt32(monthCalendar1.SelectionStart.Month);
cmdDataBaseF.Parameters.Add("#ano", SqlDbType.Int).Value = Convert.ToInt32(monthCalendar1.SelectionStart.Year);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmdDataBaseF;
System.Data.DataTable dbdatasetF = new System.Data.DataTable();
sda.Fill(dbdatasetF);
BindingSource bSourceF = new BindingSource();
bSourceF.DataSource = dbdatasetF;
dataGridView1.DataSource = bSourceF;
sda.Update(dbdatasetF);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Best regards
You can use the DATEPART function to know witch day of the week has your selected date and knowing that number is easy to solve your problem n___n
Try with this:
private void AutoLoadCalendar()
{
string constringF = #"Data Source=|DataDirectory|\cadastramentodb.sdf;Persist Security Info=False";
string QueryF =
"DECLARE #DiaSemana AS INT " +
"SET #DiaSemana=DATEPART(DW,#Fecha) " +
" " +
"SELECT * " +
"FROM Funcionarios " +
"WHERE [status] = N'Ativo' AND datafimcontrato >= DATEADD(DD,#DiaSemana*-1,#Fecha) AND datafimcontrato <= DATEADD(DD,7-#DiaSemana,#Fecha) ";
SqlCeConnection conDataBaseF = new SqlCeConnection(constringF);
SqlCeCommand cmdDataBaseF = new SqlCeCommand(QueryF, conDataBaseF);
cmdDataBaseF.Parameters.Add("#Fecha", monthCalendar1.Value);
try
{
SqlCeDataAdapter sda = new SqlCeDataAdapter();
sda.SelectCommand = cmdDataBaseF;
System.Data.DataTable dbdatasetF = new System.Data.DataTable();
sda.Fill(dbdatasetF);
BindingSource bSourceF = new BindingSource();
bSourceF.DataSource = dbdatasetF;
dataGridView1.DataSource = bSourceF;
sda.Update(dbdatasetF);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

OleDb Update requires Insert Command?

I try to updata a single row, chosen by it ID. But what I got at best is an additional row instead of an updated one.
I made several attempts. Now I got a System.InvalidOperationException claiming that a valid InsertCommand is necessary for an update, if a DataRow listing will get a new row.
To me it is the same again: Why insert? I want to update.
Can anybody give me a hint?
This is my related code:
string selectQuery = $"SELECT * FROM Records";
string updateQuery = $"UPDATE Records SET AnyContent = #AnyContent WHERE [ID] = #ID";
OleDbDataAdapter adapter = null;
OleDbCommand cmd = null;
try
{
adapter = new OleDbDataAdapter(selectQuery, ConnectionString);
cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = updateQuery;
cmd.Parameters.AddWithValue ("#AnyContent", "066066");
cmd.Parameters.AddWithValue("#ID", 2);
try
{
adapter.UpdateCommand = cmd;
nbRowsChanged = adapter.Update(content);
}
finally
{
adapter?.Close();
cmd?.Close();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
<<< Update >>>
Originally I tried it with an OleDbCommandBuilder before. But CommandBuilder created an update command, which seems to me like an insert command. This is why I tried it without CommandBuilder above. But inserting seems to follow me.
This is my old code, which is closer to where I want to get as it uses a DataTable instead of parameters:
string selectQuery = $"SELECT * FROM Records WHERE [ID] = ?";
OleDbConnection con = null;
OleDbDataAdapter adapter = null;
OleDbCommandBuilder builder = null;
try
{
adapter = new OleDbDataAdapter();
con = new OleDbConnection(ConnectionString);
adapter.SelectCommand = new OleDbCommand(selectQuery, con);
builder = new OleDbCommandBuilder(adapter);
try
{
con.Open();
nbRowsChanged = adapter.Update(content);
logText += "....InsertCommand: " + builder.GetInsertCommand().CommandText + "\n"; // Just to debug
logText += "....UpdateCommand: " + builder.GetUpdateCommand().CommandText + "\n"; // Just to debug
}
finally
{
con?.Close();
adapter?.Dispose();
}
}
catch (OleDbException e)
{
logText += "...Database Exception:\n\n" + e.Message + "\n\n";
isSuccess = false;
}
if (0 < nbRowsChanged)
{
logText += ".... Success: Updated <" + nbRowsChanged.ToString() + "> rows.\n";
isSuccess = true;
}
logText += tmpText ;
logText += "...Database: Access disposed.\n";
return isSuccess;
And this is the related trace:
LogText:
...Database: Trying to update <1> number of rows in table <Records>
....InsertCommand: INSERT INTO Records (AnyContent) VALUES (?)
....UpdateCommand: UPDATE Records SET AnyContent = ? WHERE ((ID = ?) AND ((? = 1 AND AnyContent IS NULL) OR (AnyContent = ?)))
.... Success: Updated <1> rows.
...Database: Access disposed.
NbRows Before: 5
NbRows After: 6

How to filter one dropdownlist based on another selection

I have the following code which populates the Topic dropdownlist and saves it to a cached table:
bookingData2 = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query2 = #"Select * from [DB].dbo.[top]";// columng #1 = Specialty and column #2 = Topic
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query2, conn);
SqlDataAdapter da = new SqlDataAdapter(query2, conn);
da.Fill(bookingData2);
HttpContext.Current.Cache["cachedtable2"] = bookingData2;
bookingData2.DefaultView.Sort = "Topic ASC";
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
I have the following code which populates the Specialty dropdownlist and saves it to another cached table:
bookingData = new DataTable();
DataTable DTable_List = new DataTable();
string connString = #"";
string query = #"select * from [DB].dbo.[SP]";
using (SqlConnection conn = new SqlConnection(connString))
{
try
{
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter da = new SqlDataAdapter(query, conn);
da.Fill(bookingData);
bookingData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = bookingData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
Specialty.Items.Remove("All Specialties");
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
da.Dispose();
}
catch (Exception ex)
{
string error = ex.Message;
}
}
How can I code the Specialty dropdownlist index change to do the following and save it to a cache table for quick access:
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
--> Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
}
Save bookingData2 table in ViewState or Session (I won't recommend to use session though) if it's not too heavy. Otherwise, its better you cache it or query the database again to repopulate it.
Let's assume you save bookingData2 in ViewState as follows in Page_Load
ViewState["bookingData2"] = bookingData2; // This should be before the following line
Topic.DataSource = bookingData2.DefaultView.ToTable(true, "Topic");
Then in your SelectedIndexChanged event do something like this
protected void Specialty_SelectedIndexChanged(object sender, EventArgs e)
{
//re-populate the Topic dropdownlist to display all the topics based on the following criteria:
// Where the Specialty column is either "All Specialties" OR "{specialty selected index value}"
DataTable bookingData2 = (DataTable)ViewState["bookingData2"];
Topic.DataSource = bookingData2.Where(i => i.Specialty == "All Specialties" || i.Specialty == Specialty.SelectedValue).DefaultView.ToTable(true, "Topic"); // populate only with the Topic column
Topic.DataTextField = "Topic";
Topic.DataValueField = "Topic";
Topic.DataBind();
Topic.Items.Insert(0, new ListItem("All Topics", "All Topics"));
}
Update - With Cached object
Do following in Specialty_SelectedIndexChanged event instead of where we used ViewState before.
if (HttpRuntime.Current.Cache["cachedtable2"] != null)
{
DataTable bookingData2 = HttpRuntime.Current.Cache["cachedtable2"] as DataTable;
// Rest of the code
}
I haven't tried this code. Let me know if you find any issues.
This is what solved it for me:
protected void Topic_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (Topic.SelectedIndex == 0)
{
string query = #"Specialty LIKE '%%'";
DataTable cacheTable = HttpContext.Current.Cache["cachedtable"] as DataTable;
DataTable filteredData = cacheTable.Select(query).CopyToDataTable<DataRow>();
filteredData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = filteredData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
else
{
string qpopulate = #"[Topic] = '" + Topic.SelectedItem.Value + "' or [Topic] = 'All Topics'"; //#"Select * from [DB].dbo.[table2] where [Specialty] = '" + Specialty.SelectedItem.Value + "' or [Specialty] = 'All Specialties'";
DataTable cTable = HttpContext.Current.Cache["cachedtable2"] as DataTable;
DataTable fData = cTable.Select(qpopulate).CopyToDataTable<DataRow>();
if (fData.Rows.Count > 0)
{
fData.DefaultView.Sort = "Specialty ASC";
Specialty.DataSource = fData.DefaultView.ToTable(true, "Specialty");
Specialty.DataTextField = "Specialty";
Specialty.DataValueField = "Specialty";
Specialty.DataBind();
}
Specialty.Items.Insert(0, new ListItem("All Specialties", "All Specialties"));
}
}
catch (Exception ce)
{
string error = ce.Message;
}
}

c# multiple chart error

I want to create a column chart in c#.
this is the code that i uset for that:
private void Vizualizare_profil()
{
myConn = new MySqlConnection(myConnection);
MySqlCommand selectCommand = new MySqlCommand("SELECT * FROM `gomoku`.`informatii` WHERE `id_utilizator` = '" + id_client.ToString() + "';", myConn);
MySqlDataAdapter dataAdap = new MySqlDataAdapter(selectCommand);
DataSet ds = new DataSet();
myConn.Open();
dataAdap.Fill(ds);
myConn.Close();
DataTable dt = new DataTable();
dt.Columns.Add("Nume");
dt.Columns.Add("Meciuri castigate");
dt.Columns.Add("Meciuri pierdute");
dt.Columns.Add("Meciuri remize");
if (ds.Tables[0].Rows.Count != 0)
{
label28.Text = Username;
label29.Text = ds.Tables[0].Rows[0]["nume"].ToString();
label30.Text = ds.Tables[0].Rows[0]["prenume"].ToString();
label31.Text = ds.Tables[0].Rows[0]["varsta"].ToString();
label32.Text = ds.Tables[0].Rows[0]["adresa_email"].ToString();
dt.Rows.Clear();
dt.Rows.Add("Meciuri castigate " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_castigate"]), ds.Tables[0].Rows[0]["meciuri_castigate"], 0 , 0);
dt.Rows.Add("Meciuri pierdute " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_pierdute"]), 0, ds.Tables[0].Rows[0]["meciuri_pierdute"], 0);
dt.Rows.Add("Meciuri remize " + Convert.ToString(ds.Tables[0].Rows[0]["meciuri_remiza"]), 0, 0,ds.Tables[0].Rows[0]["meciuri_remiza"]);
chart1.DataSource = dt;
chart1.Series[0].XValueMember = "Nume";
chart1.Series[0].YValueMembers = "Meciuri castigate";
chart1.Series[1].XValueMember = "Nume";
chart1.Series[1].YValueMembers = "Meciuri pierdute";
chart1.Series[2].XValueMember = "Nume";
chart1.Series[2].YValueMembers = "Meciuri remize";
}
else
MessageBox.Show("Database error!");
}
It creates perfect the first chart but if this method is called again it shows the same data.
What is the problem and what can by done?

Filter datagridview using datetimepicker?

I'm doing an application where there will be two filters.
First filter is when user will enter an ID then only the data of that ID is displayed. I've managed to done that but the problem is on the second filter I try to implement. After the user enter the ID then display the ID data, then the user can filter that data even more based dates. So I try using datetimepicker tools.
But when I choose the date, mydatagridview won't filter to show only the chosen date data. It still shows all the data from the first ID filter.
Any help will greatly appreciated.
Here is my code :
private void trackBtn_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
if (dataGridView1.Visible == true)
{
webBrowser1.Location = new Point(12, 397);
}
//DataTable dt = null;
string connoInput = textBox1.Text;
string conString = Properties.Settings.Default.BMSDATAConnectionString;
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\TrackCon\TrackCon\BMSDATA.sdf;Persist Security Info = True;Password=Gdex123$"))
{
string Ids = "conno= '" + System.Text.RegularExpressions.Regex.Replace(textBox1.Text.Trim(), #"\s*\n\s*", "' OR conno= '") + "'";
SqlCeCommand com = new SqlCeCommand("SELECT conno,cmpsno,ctrx,dsysdate,cstnno,corigin FROM BRDATA WHERE " +Ids, con);
SqlCeDataAdapter adap = new SqlCeDataAdapter(com);
DataSet set = new DataSet();
adap.Fill(set);
if (set.Tables.Count > 0)
{
bRDATABindingSource1.DataSource = set.Tables[0];
}
dataGridView1.DataSource = bRDATABindingSource1;
con.Close();
}
}
private void trackMPSbtn_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
if (dataGridView1.Visible == true)
{
webBrowser1.Location = new Point(12, 397);
}
//DataTable dt = null;
//string connoInput = textBox1.Text;
string conString = Properties.Settings.Default.BMSDATAConnectionString;
using (SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\TrackCon\TrackCon\BMSDATA.sdf;Persist Security Info = True;Password=Gdex123$"))
{
dataGridView1.DataSource = bRDATABindingSource1;
string Ids = "cmpsno= '" + System.Text.RegularExpressions.Regex.Replace(textBox2.Text.Trim(), #"\s*\n\s*", "' OR cmpsno= '") + "'";
con.Open();
SqlCeCommand com = new SqlCeCommand("SELECT conno,cmpsno,ctrx,dsysdate,cstnno,corigin FROM BRDATA WHERE " + Ids, con);
SqlCeDataAdapter adap = new SqlCeDataAdapter(com);
DataSet set = new DataSet();
adap.Fill(set);
if (set.Tables.Count > 0)
{
bRDATABindingSource1.DataSource = set.Tables[0];
}
dataGridView1.DataSource = bRDATABindingSource1;
con.Close();
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
bRDATABindingSource1.Filter = string.Format("dsysdate = #{0}#", dateTimePicker1.Value.ToLongDateString());
}
}
}
EDITED
I'm afraid the DataSource of dataGridView1 is local variable dt in both your events. But you're likely trying to filter an instance field bRDATABindingSource1. There is no more context information for me. Are you sure this is correct?
Try to use bRDATABindingSource1 instead of dt, and see if that works.

error: sql command not properly ended

I have to search the employee details, which is contained within 3 tables. I have used joins in the query query, but it shows error when I press the search button:
sql command not properly ended
c# coding:
try {
//Search Employee Details
Oracle.DataAccess.Client.OracleConnection cn = new Oracle.DataAccess.Client.OracleConnection();
cn.ConnectionString = "user id=system; password=system;";
Oracle.DataAccess.Client.OracleCommand cmd = new Oracle.DataAccess.Client.OracleCommand();
cmd.Connection = cn;
//cn = new Oracle.DataAccess.Client.OracleConnection();
cmd.CommandText = " select deposit.loanid,
form1.empedoj,
form1.empshare,
sharecapital.shareint,
sharecapital.loandt,
sharecapital.loandeduc,
sharecapital.dividend,
sharecapital.sharetot
from form1,
deposit,
sharecapital
where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "'"; // shows sql command not properly ended
Oracle.DataAccess.Client.OracleDataAdapter ada = new Oracle.DataAccess.Client.OracleDataAdapter(cmd);
System.Data.DataTable dt = new DataTable();
dt.Clear();
ada.Fill(dt);
//Display in Textbox
if (dt.Rows.Count > 0) {
txtlnid.Text = dt.Rows[0].ItemArray[0].ToString();
admdate.Text = dt.Rows[0].ItemArray[1].ToString();
txtadmamt.Text = dt.Rows[0].ItemArray[2].ToString();
txtadmint.Text = dt.Rows[0].ItemArray[3].ToString();
loandt.Text = dt.Rows[0].ItemArray[4].ToString();
txtlnamt.Text = dt.Rows[0].ItemArray[5].ToString();
txtlnint.Text = dt.Rows[0].ItemArray[6].ToString();
txtsctot.Text = dt.Rows[0].ItemArray[7].ToString();
}
if (cn.State == ConnectionState.Closed) {
cn.Open();
}
string str;
str = cmd.ExecuteScalar().ToString();
if (str != null) {
MessageBox.Show("Record Found");
} else {
MessageBox.Show("ID not Match");
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
Your SQL statement becomes
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
I suspect it should be:
SELECT DEPOSIT.LOANID,
FORM1.EMPEDOJ,
FORM1.EMPSHARE,
SHARECAPITAL.SHAREINT,
SHARECAPITAL.LOANDT,
SHARECAPITAL.LOANDEDUC,
SHARECAPITAL.DIVIDEND,
SHARECAPITAL.SHARETOT
FROM FORM1, DEPOSIT, SHARECAPITAL
WHERE DEPOSIT.LOANID(+) = SHARECAPITAL.LOANID
AND SHARECAPITAL.LOANID = '" + txtlnid.Text.Trim() + "'";
Also, you have a 3-table join without the correct join conditions, the query is highly likely to return a Cartesian product.
Have you tried putting a semicolon at the end of your query string?
cmd.CommandText = " select deposit.loanid, form1.empedoj, form1.empshare,
sharecapital.shareint, sharecapital.loandt, sharecapital.loandeduc,
sharecapital.dividend, sharecapital.sharetot from form1, deposit ,
sharecapital where deposit.loanid(+) = sharecapital.loanid = '" + txtlnid.Text.Trim() + "';";

Categories

Resources