My registration program logs people in with their name, id and "Time In:" when they scan themselves in, and hides them, but adds "Time Out: " to their name, and vice versa. What im looking to do is every time the person scans themselves "In" I want it to look at the Time "In"'s amd "out"'s and calculate thr total time IN the office.
Attached is the code :
private string CreateTimeEntry(string current)
{
var indexIn = current.LastIndexOf("Time In : "); // Get the last index of the word "in"
var indexOut = current.LastIndexOf("Time Out : "); // Get the last index of the word out
string timeIn = current + " " + "Time In : ";
string timeOut = current + " " + "Time Out : ";
if (indexOut > indexIn)
{
// if the last "out" comes after the last "in"
return timeIn;
}
else
{
// If the last "in" comes after the last "out"
return timeOut;
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
bool found = false;
System.DateTime resultTime1 = new System.DateTime(;
foreach (var item in listBox1.Items)
{
var itemEntry = item.ToString();
string newEntry = CreateTimeEntry(itemEntry) + DateTime.Now.ToString("HH:mm") + " " + "Total Time: " + resultTime1 ;
if (itemEntry.Contains(returnValue.ToString()))
{
var indexIn = itemEntry.LastIndexOf("Time In : ");
var indexOut = itemEntry.LastIndexOf("Time Out : ");
if (indexOut > indexIn)
{
listBox2.Items.Remove(item);
listBox1.Items.Add(newEntry);
found = true;
break;
}
else
{
listBox1.Items.Remove(item);
listBox2.Items.Add(newEntry);
found = true;
break;
}
}
}
if (!found)
{
string newEntry2 = "";
foreach (string str in listBox2.Items)
{
var itemEntry2 = str;
newEntry2 = CreateTimeEntry(itemEntry2) + DateTime.Now.ToString("HH:mm");
//if (listBox2.Items.Contains(returnValue.ToString()))
if (listBox2.Items.Contains(str) && str.Contains(textBox1.Text))
{
var indexIn = itemEntry2.LastIndexOf("Time In : ");
var indexOut = itemEntry2.LastIndexOf("Time Out : ");
if (indexOut > indexIn)
{
listBox2.Items.Remove(str);
listBox1.Items.Add(newEntry2);
found = true;
break;
}
}
}
var itemEntry = listBox1.Items.ToString();
var itemEntry1 = listBox2.Items.ToString();
if (!listBox1.Items.Contains(newEntry2))
{
listBox1.Items.Add(returnValue + " " + "Time In : " + DateTime.Now.ToString("HH:mm"));
}
}
}
textBox1.Clear();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName);
foreach (object item1 in listBox1.Items)
SaveFile.WriteLine(item1.ToString());
SaveFile.Flush();
SaveFile.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
You can get the difference between two DateTime objects using the following:
TimeSpan timePassed = timeOut.Subtract(timeIn);
where timeOut and timeIn are DateTime objects.
If you need the difference (or either of the times) displayed somewhere as a string, I would recommend converting them to strings only after doing the calculations that you need. Always work with strongly typed objects when possible.
Related
I tried:
System.Web.UI.Page FormPage;
object FormControl = FormPage.FindControl("lblUserNames");
object literalControl = FormPage.FindControl("litMessages");
But it is throwing an error: "Use of unassigned local variable 'FormPage'"
So how do I set the textbox/label value in a static method?
The whole source:
[WebMethod]
public static void DeleteItem()
{
HttpCookie reader = HttpContext.Current.Request.Cookies["roomId"];
string query = "[Get_Messages]";
SqlCommand cmd = new SqlCommand(query);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#roomId", reader.Value);
GetData(cmd);
}
Get data from database to dataset and bind it to div.
private static DataSet GetData(SqlCommand cmd)
{
int cntr = 0;
HttpCookie cookieUserName = HttpContext.Current.Request.Cookies["userName"];
string username = cookieUserName.Value;
System.Web.UI.Page FormPages;
object FormsControl = FormPages.FindControl("lblUserNames");
string strConnString = ConfigurationManager.ConnectionStrings["LinqChatConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds, "Messages");
return ds;
if (ds.Tables[0].Rows.Count != 0)
{
StringBuilder sb = new StringBuilder();
int i = (ds.Tables[0].Rows.Count - 1);
for (int j = 0; j <= i; j++)
{
string personName = ds.Tables[0].Rows[j]["Username"] == null ? "" : ds.Tables[0].Rows[j]["Username"].ToString();
string gender = ds.Tables[0].Rows[j]["Sex"] == null ? "" : ds.Tables[0].Rows[j]["Sex"].ToString();
string message = ds.Tables[0].Rows[j]["Text"] == null ? "" : ds.Tables[0].Rows[j]["Text"].ToString();
if (cntr == 0)
{
if (username == personName)
{
sb.Append("<div style='padding: 10px;text-align:right'>");
}
else
{
sb.Append("<div style='padding: 10px;'>");
}
cntr = 1;
}
else
{
if (username == personName)
{
sb.Append("<div style='background-color: #EFEFEF;padding: 10px;text-align:right'>");
}
else
{
sb.Append("<div style='background-color: #EFEFEF;padding: 10px;'>");
}
cntr = 0;
}
((System.Web.UI.WebControls.Label)FormControl).Text = "<span style='color: Blue;'><b line-height:22px>" + personName + "</b></span>";
string lblUserNames = ((System.Web.UI.WebControls.Label)FormControl).Text;
//lblUserNames.Text
((System.Web.UI.WebControls.Label)FormControl).Visible = true;
//lblUserNames.Visible = true;
if (gender.ToLower() == "m")
{
if (username == personName)
{
sb.Append(message + "</div>");
}
else
{
sb.Append("<img src='Images/manIcon.gif' style='vertical-align:middle;' alt=''> " + lblUserNames + " " + message + "</div>");
}
}
else
{
if (username == personName)
{
sb.Append(message + "</div>");
}
else
{
sb.Append("<img src='Images/womanIcon.gif' style='vertical-align:middle' alt=''> " + lblUserNames + " " + message + "</div>");
}
}
}
((System.Web.UI.WebControls.Literal)FormsControl).Text = sb.ToString();
((System.Web.UI.WebControls.Label)FormControl).Visible = false;
}
else
{
((System.Web.UI.WebControls.Label)FormControl).Visible = false;
}
}
}
}
}
You could try to set it?
FormPage page = new FormPage();
object FormControl = page.FindControl("lblUserNames");
object literalControl = page.FindControl("litMessages");
Here is my current code behind for the OnRowUpdating event and SQL statement to update the database. It is throwing an exception:
System.NullReferenceException: Object reference not set to an instance of an object.error
Code:
protected void GV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtSu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox1"); // each textbox refers to the Am then Pm day
TextBox txtSu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox2");// sun pm
TextBox txtMo = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox3");// mon am
TextBox txtMo1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox4");//mon pm
TextBox txtTu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox5");
TextBox txtTu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox6");
TextBox txtWe = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox7");
TextBox txtWe1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox8");
TextBox txtTh = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox9");
TextBox txtTh1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox10");
TextBox txtFr = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox11");
TextBox txtFr1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox12");
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
TextBox txtSa1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox14");
string sql = "UPDATE tblEMPLOYEE SET EmployeeID=#ID, " +
"AvailSun=#AvSu, " +
"AvailSun1=#AvSu1, " +
"AvailMon=#AvMo, " +
"AvailMon1=#AvMo1, " +
"AvailTues=#AvTu, " +
"AvailTues1=#AvTu1, " +
"AvailWedn=#AvWe, " +
"AvailWedn1=#AvWe1, " +
"AvailThurs=#AvTh, " +
"AvailThurs1=#AvTh1, " +
"AvailFri=#AvFr, " +
"AvailFri1=#AvFr1, " +
"AvailSat=#AvSa, " +
"AvailSat1=#AvSa1 " +
"WHERE EmployeeID=#ID";
CMethods.executeNonQuery(sql, "#ID", txtID.Text, "#AvSu", txtSu.Text, "#AvSu1", txtSu1.Text, "#AvMo", txtMo.Text, "#AvMo1", txtMo1.Text, "#AvTu", txtTu.Text, "#AvTu1", txtTu1.Text, "#AvWe", txtWe.Text, "#AvWe1", txtWe1.Text, "#AvTh", txtTh.Text, "#AvTh1", txtTh1.Text, "#AvFr", txtFr.Text, "#AvFr1", txtFr1.Text, "#AvSa", txtSa.Text, "#AvSa1", txtSa1.Text, "#ID", ID);
GV.EditIndex = -1;
fillUsers();
}
private void fillUsers()
{
GV.DataSource = CMethods.returnTable("SELECT * FROM tblEMPLOYEE WHERE EmployeeID=" + lblEmployee.Text);
GV.DataBind();
}
In Cmethods
public static class CMethods
{
public static DataTable returnTable(String CommandText, params Object[] values)
{
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "tbl");
return ds.Tables["tbl"];
}
public static bool executeNonQuery(String CommandText, params Object[] values)
{
bool bln = true;
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
bln = false;
}
finally
{
con.Close();
}
return bln;
}
public static double returnValue(string str)
{
double dblTemp = 0.0D;
string strTemp = String.Empty;
bool blnFirstDec = false;
bool blnFirstNeg = false;
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == "-")
{
blnFirstNeg = true;
}
if (IsNumeric(str.Substring(i, 1)) || str.Substring(i, 1) == ".")
{
if (str.Substring(i, 1) == ".")
{
if (!blnFirstDec)
{
blnFirstDec = true;
strTemp += ".";
}
}
else
{
strTemp += str.Substring(i, 1);
}
}
}
FindControl control may not return control if you not provide correct control id
for example you have given txtBo13(missing x) but actually you may have txtBox13,
so below code return null for txtSa
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBo13");
when you call Text property of txtSa you will get NullReferenceException
if you have given id as txtBox13, change the code accordingly
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
And also you may have forgot to set #student parameter value
The program I have written is a register, which when a bar code is a scanned, will go to the database and pull out the persons name and I.D. No. and also list a "Time In:" at which time they scanned in. And then when they scan a second time it will add a part "Time out:" like such:
Peters, Alastair (242242) Time In : 14:50 Time Out : 14:50 Time In : 14:50
What i am looking for it to do is when i first scan in you will see :
Peters, Alastair (242242) Time In : 14:50
and then when you scan a second time it will add in the Time Out : and then remove the entire line and store it in a second listbox, so it does not show when the person is not in.
And then when the person scans in (the 3rd time) it will re-list the previous line, but with the new Time In
Any suggestions or ideas would be very helpful!
Here is my code:
private string CreateNewEntry(string current)
{
var indexIn = current.LastIndexOf("Time In : "); // Get the last index of the word "in"
var indexOut = current.LastIndexOf("Time Out : "); // Get the last index of the word out
if (indexOut > indexIn)
{
return current + " "+"Time In : "; // if the last "out" comes after the last "in"
}
else
{
// If the last "in" comes after the last "out"
return current + " " +"Time Out : ";
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
string txtend = textBox1.Text;
if (e.KeyChar == 'L')
{
DBConnection.Open();
}
if (DBConnection.State == ConnectionState.Open)
{
if (textBox1.Text.Length != 6) return;
{
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
bool found = false;
foreach (var item in listBox1.Items)
{
var entry = item.ToString();
if (entry.Contains(returnValue.ToString()))
{
listBox1.Items.Remove(item);
listBox1.Items.Add(CreateNewEntry(entry) + DateTime.Now.ToString("HH:mm"));
found = true;
break;
}
}
if (!found)
{
listBox1.Items.Add(returnValue + " " + "Time In : " + DateTime.Now.ToString("HH:mm"));
}
textBox1.Clear();
System.IO.StreamWriter SaveFile = new System.IO.StreamWriter(fullFileName);
foreach (object item in listBox1.Items)
SaveFile.WriteLine(item.ToString());
SaveFile.Flush();
SaveFile.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
Current_Attendance_Label.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
}
I understand that the starting bit (e.g., "Peters, Alastair (242242)") is unique and remains constant; in that case, you can use FindString. Sample Code:
int curIndex = listBox1.FindString("Peters, Alastair (242242)");
string wholePetersRecord = "";
if (curIndex >= 0)
{
wholePetersRecord = listBox1.Items[curIndex].ToString();
listBox1.Items.RemoveAt(curIndex);
}
This code will find, store in wholePetersRecord and delete the first item starting with "Peters, Alastair (242242)" ("Peters, Alastair (242242) Time In : 14:50 Time Out : 14:50 Time In : 14:50", for instance).
I found strange is that when I check some of the checkbox (generated HTML code), the sub function did not alert (or display message) which checkbox is being checked.
Am I missing something?
Inside the WebForm.aspx
<script type="text/javascript">
function sub()
{
for (i=0; i<arrChecks.length; i++)
{
var attribute = arrChecks[i].getAttribute("xid")
if (attribute == elementName)
{
// if the current state is checked, unchecked and vice-versa
if (arrChecks[i].checked)
{
arrChecks[i].checked = false;
} else {
arrChecks[i].checked = true;
alert("Checked!");
}
} else {
arrChecks[i].checked = false;
}
}
}
</script>
Inside the WebForm.cs
protected void ButtonCheckDate_Click(object sender, EventArgs e)
{
SqlConnection conn = ConnectDB("Data Source=JACKSERVERA;Initial Catalog=tablea;User Id=tableuser;Password=tablepassword");
if ((TextBox2.Text != null) && (TextBox2.Text != ""))
{
try
{
String res = "";
SqlCommand command = conn.CreateCommand();
SqlDataReader reader;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = "SELECT * from overviewtable where [dated] = #PDATED";
command.Parameters.AddWithValue("#PDATED", TextBox2.Text);
command.Connection = conn;
sqlstmt.Text = command.CommandText;
conn.Open();
reader = command.ExecuteReader();
if (reader.HasRows)
{
res = res + "<form name=\"input\" runat=\"server\"><table border=1>";
while (reader.Read())
{
res = res + "<tr>";
string thetime = (string)reader["time"];
string thevenue = (string)reader["venue"];
int numfreeseat = (int)reader["freeseat"];
int occupiedseat = 0;
SqlCommand bkcommand = conn.CreateCommand();
SqlDataReader bookinglist;
bkcommand.CommandType = System.Data.CommandType.Text;
bkcommand.CommandText = "SELECT count(*) from venuea where [dated] = #PDATED";
bkcommand.Parameters.AddWithValue("#PTIME", thetime);
bkcommand.Connection = conn;
sqlstmt.Text = bkcommand.CommandText;
bookinglist = bkcommand.ExecuteReader();
while (bookinglist.Read())
{
if (bookinglist.HasRows)
{
occupiedseat = (int)bookinglist.GetValue(0);
}
}
int leftnumofseat = numfreeseat - occupiedseat;
string color = "";
Boolean fullyoccupied = false;
if (leftnumofseat > 0)
{
if (leftnumofseat == numfreeseat)
{
// white
color = "#FFFFFF";
}
else
{
// light gray - partial occupied
color = "#B8B8B8";
}
}
else
{
// dark gray - fully occupied
color = "#505050";
fullyoccupied = true;
}
res = res + "<td bgcolor=\"" + color + "\">";
res = res + "Available: " + leftnumofseat + "/" + numfreeseat + "";
res = res + "</td>";
string checkboxval = TextBox2.Text + "_" + thetime + "_" + thevenue;
res = res + "<td>";
if (fullyoccupied == false)
{
res = res + "<input type=\"checkbox\" name=\"xid\" value=\"" + checkboxval + "\" runat=\"server\" />";
}
else
{
res = res + "FULL";
}
res = res + "</td>";
res = res + "</tr>";
}
res = res + "</table><input type=\"submit\" value=\"Submit\" OnClick=\"sub\" runat=\"server\"></form>";
}
LabelDateSelection.Text = res;
conn.Close();
}
catch (Exception err)
{
errormsg.Text = err.Message;
}
}
else
{
LabelDateSelection.Text = "Enter Date!";
}
}
Take out this part from you code & see if it works runat=\"server\"
i am not sure if you can create and ASP.net server control as you are trying too & you are sending output to the client while runat=\"server\" is rendered by the server . check you HTML code & see how it looks.
Create HTML control dynamically or create simple HTML control if that can work with your case.
look at the example how to pragmatically create controls
http://msdn.microsoft.com/en-us/library/kyt0fzt1%28v=vs.100%29.aspx
In addition to the points made by KnowledgeSeeker, you can't create asp controls in that style.
You can either get the values of the created checkboxes by using the FindControl method to locate the element and then get the value from it or in the C# add code similar to:
for (int i = 0; i < 5; i++)
{
CheckBox chk = new CheckBox();
chk.ID = Convert.ToString(i);
chk.Text = Convert.ToString(i);
form1.Controls.Add(chk);
}
In that instance you are looping from 0 to 5 and creating checkboxes and adding those controls to the form.
I wrote this formula here but for some reason it sums ALL the values in the amt column instead of the one that has the itemcolumn string. Any ideas?
foreach (DataGridViewRow row in itemGrid.Rows)
{
if (itemGrid.Rows[e.RowIndex].Cells["itemColumn"].Value.ToString() == itemcolumn)
total += Convert.ToDecimal(row.Cells["Amt"].Value.ToString());
}
Here's the full code so you can see what's going on here.
private void itemGrid_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//
// [This string compares amt and amtvalue on Cell edit]
//
if (itemGrid.CurrentCell.ColumnIndex == 5 && isCalled)
{
// Prevents loop.
isCalled = false;
decimal total = 0;
string itemcolumn = String.Empty;
{
foreach (DataGridViewRow row in itemGrid.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Selected)
{
itemcolumn = Convert.ToString(row.Cells["itemColumn"].Value);
string strName = vendorBox.Text;
string Select = "select sum(case allocated when 'Received' then amt when 'Shipped' then -amt end) as amt from lineitem WHERE item='" + itemcolumn + "';";
MySql.Data.MySqlClient.MySqlConnection conDatabase = new
MySqlConnection(ConnectionString.connString);
MySql.Data.MySqlClient.MySqlCommand cmdDatabase = new
MySql.Data.MySqlClient.MySqlCommand(Select, conDatabase);
try
{
conDatabase.Open();
MySql.Data.MySqlClient.MySqlDataReader rdrRepairOrder;
rdrRepairOrder = cmdDatabase.ExecuteReader();
while (rdrRepairOrder.Read())
{
string rowz5 = string.Format("{0}", rdrRepairOrder.GetString(0));
string wut5 = rowz5.ToString();
itemamt = Convert.ToInt32(wut5);
}
rdrRepairOrder.Close();
conDatabase.Close();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show("Error " + ex.Number + " has occurred: " + ex.Message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
}
// Converts amt column.
// amt = The cell amount.
// itemamt = What's on the SQL table.
foreach (DataGridViewRow row in itemGrid.Rows)
{
if (itemGrid.Rows[e.RowIndex].Cells["itemColumn"].Value.ToString() == itemcolumn) total += Convert.ToDecimal(row.Cells["Amt"].Value.ToString());
}
MessageBox.Show("Total is: " + total.ToString());
int amt;
string amtz = itemGrid.Rows[e.RowIndex].Cells["Amt"].Value.ToString();
amt = Convert.ToInt32(amtz);
int value;
value = itemamt - amt;
if (value < 0)
{
MessageBox.Show("Cannot allocate more than what it is in inventory. You have " + itemamt.ToString() + " in stock.");
itemGrid[5, itemGrid.CurrentCell.RowIndex].Value = itemamt;
}
}
isCalled = true;
}
Instead of itemGrid.Rows[e.RowIndex], try using row in your condition.