I want to find current day of week in c# ASP.Net like:
System.DateTime.Now.DayOfWeek.ToString();
This code works well in a console application, but when I try to store the value of this line in a string in ASP.Net website it returns nothing.
Can anyone help?
StringBuilder message = null;
protected void Page_Load(object sender, EventArgs e)
{
var dayofweek = System.DateTime.Now.DayOfWeek.ToString();
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader = null;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
message = new StringBuider();
while (reader.Read())
{
message.Append(reader["lec"].ToString());
//question what are you using message for ...?
Label3.Text = dayofweek;
}
reader.Close();
}
catch (Exception ex)
{
Response.Write(ex.Mesage);
}
finally
{
sqlconne.Close();
// you neeed to Dispose of all other objects here too
// StringBuilder Object
// SqlDataReader Object
//SqlCommand Object..
//Look into wrapping your Connection / Command Sql Dataobject around a using() {}
}
I want to use current day in where clause SQL Query to get data relevant to current day from database table.
I used var as
protected void Page_Load(object sender, EventArgs e)
{
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
var testDay = DateTime.Now.DayOfWeek.ToString();
// string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
string selectSQL = string.Format("SELECT lec FROM schedule WHERE [day]= {0}", testDay);
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
message += reader["lec"].ToString();
Label3.Text = testDay;
}
reader.Close();
}
catch
{
}
finally
{
sqlconne.Close();
}
It works fine for me.
Wep page is the value defined as a public , static, or property..
if you write
var testDay = DateTime.Now.DayOfWeek.ToString();
the results will = "Friday";
if everything is working fine when you remove the where clause then change the Where clause to be something like this
string selectSQL = string.Format("SELECT lec FROM schedule WHERE dbo.schedule.day = {0} ", testDay);
I would also change the name of the field day to something like DayName or something if day is a Reserved word don't use it..
look at this link for Reserved Words in SQL Reserved SQL Words
Also try changing your sql string to this
string selectSQL =
string.Format("SELECT lec FROM schedule WHERE [day]= {0}", dayofweek);
As an integer value (system sets sunday's as 0) =
int day = (int)DateTime.Now.DayOfWeek;
Related
I have another question posted where my query would not return the results into my sealresult Label. So I figured to ask it in a different way because I still cannot figure this out. I have the following code, it runs perfectly when the button "Search" is clicked and returns the query result. However, I have a textBox with an Id of receiptbox and I want to enable an user to input text and that be placed into the query to gather the result into the sealresult Label. How do I accomplish this? I want user input where it says RE00007544 from a textbox labeled receiptbox.
protected void receiptbox_TextChanged(object sender, EventArgs e)
{
}
protected void sealresultquery_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void searchbutton_Click(object sender, EventArgs e)
{
sealresult.Text = "";
string connString = #"Data Source=SQL;Initial Catalog=mydatabase;User ID=admin;Password=******";
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = 'RE00007544'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand(query, conn);
using (conn)
{
try
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while(reader.Read())
{
sealresult.Text += reader[0].ToString();
}
reader.Close();
}
catch(Exception ex)
{
querystatus.Text = ex.Message;
}
}
}
If I understand, I think the simplest modification to the code you provided would be:
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = '" + receiptbox.Text + "'";
However, it's not the most secure way. You shouldn't be this trusting with user input.
Learn to use parameters which will save you from sql injections.
Change your code like below.
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = #number";
//define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#number";
param.Value = receiptbox.Text.Trim();
//add new parameter to command object
comm.Parameters.Add(param);
First post here. I'm trying to create a website that fetches data from an Oracle database and returns some tables. I was able to connect my database fine and made a DataConnector that returns a list of CodeDesc objects. My main problem right now is simply displaying that data to the screen, preferably in the form of a drop down list but I'm using a GridView for now.
Here's my front end:
protected void Button1_Click(object sender, EventArgs e)
{
DataConnector dc = new DataConnector();
GridView2.DataSource = dc.getCodeTypes();
GridView2.DataBind();
}
When I click the button, nothing is generated and the debugger only says "Exception thrown: 'System.ArgumentException' in Oracle.DataAccess.dll" Any help would be appreciated. This is my first time doing web development and it's been a struggle to get even this far. I'm using Visual Studio 2015
Back End:
//Create datatable to get info from db & return results
public List<CodeDesc> getCodeTypes()
{
try
{
OracleConnection con = new OracleConnection(connString);
con.Open();
string query = "select id, descr from code_desc where code_type_id = 0";
// Create the OracleCommand
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
// Execute command, create OracleDataReader object
OracleDataReader reader = cmd.ExecuteReader();
List<CodeDesc> L = new List<CodeDesc>();
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
// Clean up
reader.Dispose();
cmd.Dispose();
con.Dispose();
System.Diagnostics.Debug.WriteLine(L);
return L;
}
catch (Exception ex)
{
// catch clause here...
}
}
CodeDesc:
public class CodeDesc
{
public int id { get; set; }
public string description { get; set; }
}
Any help would be great.
You never set the query string to the CommandText property of the OracleCommand. Of course this can only result in an exception when you try to execute your command.
Said that, remember that every disposable object should be enclosed in a using statement. This is very important in case of exceptions because the correct closing and disposing is executed automatically exiting from the using block
public List<CodeDesc> getCodeTypes()
{
try
{
List<CodeDesc> L = new List<CodeDesc>();
string query = "select id, descr from code_desc where code_type_id = 0";
using(OracleConnection con = new OracleConnection(connString))
using(OracleCommand cmd = new OracleCommand(query, con))
{
con.Open();
// Execute command, create OracleDataReader object
using(OracleDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
CodeDesc c = new CodeDesc();
c.id = reader.GetInt32(0);
c.description = reader.GetString(1);
L.Add(c);
}
}
}
System.Diagnostics.Debug.WriteLine(L);
return L;
}
I'm trying to get these textboxes to show data from a database, i'm able to show the data but everytime I try to update it won't save. Here's what i've done
private void ClubRecord_Load(object sender, EventArgs e)
{
try
{
sConnection = "Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = Eastern_Property_Maintenance.mdb";
dbConn = new OleDbConnection(sConnection);
dbConn.Open();
sql = "SELECT * FROM Club ORDER BY CompanyName, CompanyAddress, CompanyPhone;";
dbCmd = new OleDbCommand();
dbCmd.CommandText = sql;
dbCmd.Connection = dbConn;
dbreader = dbCmd.ExecuteReader();
while (dbreader.Read())
{
string CompanyName = dbreader["CompanyName"].ToString();
string CompanyAddress = dbreader["CompanyAddress"].ToString();
string CompanyPhone = dbreader["CompanyPhone"].ToString();
txtCompanyName.Text = CompanyName;
txtCompanyAddress.Text = CompanyAddress;
txtCompanyPhone.Text = CompanyPhone;
}
dbreader.Close();
// dbConn.Close();
}
catch (System.Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = "UPDATE [Club] SET [CompanyName]= #CompanyName,[CompanyAddress]=#CompanyAddress,[CompanyPhone]=#CompanyPhone";
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbCmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
Any help would be greatly appreciated thanks.
It is a subtle typo error, but I think that there is something to learn here, so I want to give a full answer:
You create a command called dbcmd
OleDbCommand dbcmd = new OleDbCommand(Update, dbConn);
but then you fill the parameter collection of a different command dbCmd and executes this one.
dbCmd.Parameters.AddWithValue("#CompanyName", companyName);
dbCmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbCmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
C# is case sensitive, so the twos are not the same command, but how does it lead to the failed update is worth to look at.
You have declared a global OleDbCommand variable named dbCmd and this variable is still set to the SELECT query used to load the textboxes. So, when you call ExecuteNonQuery it does not update anything.
You could fix the problem simply changing all the references in the updated code from dbCmd to dbcmd. But, the lesson to learn here is, when possible avoid to use global variables.
The Connection is another example of a global variable and this is worst because it is left open after the initial form load. Don't do that. Connectiosn keep valuable system resources locked and thus should be closed immediately after usage applying the using statement pattern
private void btnConfirmChanges_Click(object sender, EventArgs e)
{
string companyName = txtCompanyName.Text;
string companyAddress = txtCompanyAddress.Text;
string companyPhone = txtCompanyPhone.Text;
string Update = #"UPDATE [Club] SET [CompanyName]= #CompanyName,
[CompanyAddress]=#CompanyAddress,
[CompanyPhone]=#CompanyPhone"; // A where here should be mandatory
using(OleDbConnection dbConn = new OleDbConnection(aGlobalConnectionStringWouldBeSafeHere))
using(OleDbCommand dbcmd = new OleDbCommand(Update, dbConn))
{
dbcmd.Parameters.AddWithValue("#CompanyName", companyName);
dbcmd.Parameters.AddWithValue("#CompanyAddress", companyAddress);
dbcmd.Parameters.AddWithValue("#CompanyPhone", companyPhone);
try
{
dbcmd.ExecuteNonQuery();
MessageBox.Show("Update Complete");
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
return;
}
}
}
By the way, I hope that your table contains only one record because without a WHERE clause you update every record present with the values of your textboxes.
I want to search some input in a data table and if exact data is found then I want to put those data into another table. If not, I will simply clear the corresponding TextBox. I have done theses so far.
private void btn_InputConfirm_Click(object sender, EventArgs e) {
string strConnection = #"Data Source=F_NOOB-PC\;Initial Catalog=ComShopDB;Integrated Security=True";
SqlConnection objcon = new SqlConnection(strConnection);
try {
string strcmd1 = "SELECT partID,partAvailable FROM Parts WHERE partID LIKE '" + txtbox_ProductSerial.Text + "'AND partAvailable ='yes'";
SqlCommand objcmd1 = new SqlCommand(strcmd1, objcon);
objcon.Open();
objcmd1.ExecuteNonQuery();
objcon.Close();
}
catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
Some help will be very much appreciated. Thanks in advance.
You can use a DataTable, use ExecuteReader method and load all records into DataTable, then use AsEnumerable and some LINQ you can get your results as a List.
DataTable dt = new DataTable();
var reader = objcmd1.ExecuteReader();
if(reader.HasRows)
{
dt.Load(reader);
var myValues = dt.AsEnumerable()
.Select(d => new {
Id = d["partID"],
Available = d["partAvailable"]
}).ToList();
}
Also you should consider using parameterized queries instead to prevent SQL Injection Attacks.
The easiest is to use DataAdapter and then use its Fill() function on a DataTable or DataSet. You do not need to open and close the connection as the Fill() function will do that for you:
private void btn_InputConfirm_Click(object sender, EventArgs e)
{
string strConnection = #"Data Source=F_NOOB-PC\;Initial Catalog=ComShopDB;Integrated Security=True";
SqlConnection objcon = new SqlConnection (strConnection);
try
{
//Writing command//
string strcmd1 = "SELECT partID,partAvailable FROM Parts WHERE partID LIKE '" + txtbox_ProductSerial.Text + "'AND partAvailable ='yes'";
System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(strcmd1, objcon);
System.Data.DataSet ds = new System.Data.DataSet();
aa.Fill(ds);
}
catch ( Exception ex )
{
MessageBox.Show (ex.Message);
}
private void button1_Click(object sender, EventArgs e)
{
DataSet1 ds = new DataSet1();
MySqlConnection con = new MySqlConnection();
con.ConnectionString = "server=localhost;database=SpeedKnotting;uid=root;password=chandra";
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandText = "SELECT * FROM invoice";
myread = cmd.ExecuteReader();
if(myread.HasRows)
{
while (myread.Read())
{
String date = myread["date1"].ToString();
String slip_no = myread["slip_no"].ToString();
String loom_no = myread["loom_no"].ToString();
String count = myread["count"].ToString();
String ends = myread["ends"].ToString();
String knotting = myread["knotting"].ToString();
String transport = myread["transport"].ToString();
String passing =myread["passing"].ToString();
String total = myread["total"].ToString();
ds.DataTable1.Rows.Add(date, slip_no, loom_no, count, ends, knotting, transport, passing, total);
}
myread.NextResult();
}
myread.Close();
con.Close();
CrystalReport1 rp = new CrystalReport1();
rp.SetDataSource(ds);
crystalReportViewer1.ReportSource = rp;
crystalReportViewer1.Refresh()
}
/*here i get the values from DB to the above string but im not able to add to the table in dataset
*/
Just replace line
ds.DataTable1.Rows.Add(date, slip_no, loom_no, count, ends, knotting, transport, passing, total);
to
ds.DataTable1.Rows.Add(date1, slip_no, loom_no, count, ends, knotting, transport, passing, total);
I think there was typo. Check and let me know.