Payroll System - 'clock out' functionality - c#

I am working on designing a payroll system using access database as back end.
Currently, I am facing problems implementing a 'clock out' functionality.
The 'clock in' button inserts the time in the database. However, when the 'clock out' button is clicked, it inserts the data into a new row. Is there any there any way to avoid this and to update the existing last row considering the Employee name. I have tried to approach this using different methods and so far I have not been able to solve it.
Is there any way to rectify this?
I think I would have to implement a loop somewhere to check emp name, clock in and locate null values in clock out field. Not sure though.
Please advise.
My code are as follows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class timecards : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
{
if (Session["ID"] != null && Session["ID"].ToString() != "")
{
PanelUsersInfo.Visible = true;
}
else
{
PanelUsersInfo.Visible = false;
}
empLabel.Visible = false;
mainPagebutton.Visible = false;
logoutButton.Visible = false;
if (Session["Title"] == null || Session["Names"] == null)
{
clockPanel.Visible = false;
return;
}
else
{
mainPagebutton.Visible = true;
logoutButton.Visible = true;
empLabel.Visible = true;
empLabel.Text = "<b>Hi, " + Session["Names"].ToString() + "</b>";
nameLabel.Text = Session["Names"].ToString();
clockinLabel.Text = DateTime.Now.ToString("HH:mm");
Label1.Text = clockinLabel.Text;
}
}
}
protected void mainPage_Click(object sender, EventArgs e)
{
Response.Redirect("employeeLoggedin.aspx");
}
protected void logout_Click(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("default.aspx");
}
protected void clockinButton_Click(object sender, EventArgs e)
{
informLabel.Text = "Clocked in at " + Label1.Text + "";
Label1.Visible = false;
Label2.Visible = false;
clockinButton.Enabled = false;
clockoutButton.Enabled = true;
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + Page.Server.MapPath("App_Data\\database.mdb");
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString);
System.Data.OleDb.OleDbCommand cmd = conn.CreateCommand();
cmd.Parameters.Add("Employee", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Employee"].Value = nameLabel.Text;
cmd.Parameters.Add("Clockin", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Clockin"].Value = clockinLabel.Text;
cmd.CommandText = "INSERT INTO [timecard] ([Employee], [Clockin]) VALUES (#Employee, #Clockin)";
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
protected void clockoutButton_Click(object sender, EventArgs e)
{
clockoutLabel.Visible = true;
clockoutLabel.Text = "You have now been clocked out.";
informLabel.Visible = false;
Label1.Visible = false;
clockoutButton.Enabled = false;
infoLabel.Visible = true;
infoLabel.Text = "If you want to clock in again, please select timecard option from the main employee page.";
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" + "data source=" + Page.Server.MapPath("App_Data\\database.mdb");
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connectionString);
System.Data.OleDb.OleDbCommand cmd = conn.CreateCommand();
cmd.Parameters.Add("Employee", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Employee"].Value = this.nameLabel.Text;
//String x = DateTime.Now.ToString("HH:mm");
cmd.Parameters.Add("Clockout", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["Clockout"].Value = this.clockinLabel.Text;
cmd.CommandText = "UPDATE [timecard] SET [Employee]=#Employee, [Clockout]=#Clockout";
conn.Open();
int numberOfRows = cmd.ExecuteNonQuery();
conn.Close();
}
}

If both buttons are INSERTing records then both buttons are running the same code. Check your .aspx page to see if both buttons happen to have the same onClick= attribute.

Thank you all who helped and provided suggestions to overcome the difficulty I was encountering.
Apparently, I found a solution. It's is better to store the values as string and then use WHERE clause to update it. For some reason, it will not directly take values from the textfields.

Related

Unable to extract the records the second time I run using the same user id

It only can be called once. where did I gone wrong? The second time it executes, no text appears. The Login and Site.Master are two different partial classes. I am kind of confounded on how to solve this.
Login.aspx
public partial class Login : System.Web.UI.Page
{
SqlDataReader dR;
DatabaseMgmt drObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void submitButton_Click(object sender, EventArgs e)
{
string strEmail, strPwd;
int intShopperID;
strEmail = txtEmail.Text.ToLower();
strPwd = txtPwd.Text.Trim();
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email ="+ "'" + strEmail + "'" + "AND Passwd ="+ "'"+ strPwd + "'";
dR = drObj.ExecuteSelect(strSqlCmd);
if(dR.Read())
{
intShopperID = Convert.ToInt32(Session["ShopperID"]);
Session["ShopperID"]=intShopperID;
Response.Redirect("Default.aspx");
}
else
{
intShopperID = 0;
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
dR.Close();
}
}
Site.Master
public partial class Site : System.Web.UI.MasterPage
{
DatabaseMgmt dBObj = new DatabaseMgmt();
protected void Page_Load(object sender, EventArgs e)
{
if (Session["ShopperID"] != null)
{
string strSqlCmd;
strSqlCmd = "SELECT Name FROM Shopper WHERE ShopperID = " + Session["ShopperID"];
lblWelcome.Text = "Welcome Eric";
logoutButton.Visible = true;
loginButton.Visible = false;
regButton.Visible = false;
}
else
{
logoutButton.Visible = false;
loginButton.Visible = true;
regButton.Visible = true;
lblWelcome.Text = "";
}
}
Display Welcome Message
First Run
Second Run
database
I did not see where you are reading the ShopperID from the database. Perhaps that is your issue. ???
To address the Parameterisation issue, I think you should consider something more like this:
public int GetShopperID(System.String strEmail, System.String strPwd) {
int result = 0;
string strSqlCmd = "SELECT ShopperID FROM Shopper WHERE Email = #Email AND Passwd = #Passwd";
using (var cmd = new System.Data.SqlClient.SqlCommand(strSqlCmd, new System.Data.SqlClient.SqlConnection(_databaseConnection))) {
cmd.Parameters.Add("#Email", System.Data.SqlDbType.VarChar, 50);
cmd.Parameters.Add("#Passwd", System.Data.SqlDbType.VarChar, 50);
cmd.Parameter["#Email"].Value = strEmail;
cmd.Parameter["#Passwd"].Value = strPwd;
cmd.Connection.Open();
using (var reader = cmd.ExecuteReader()) {
if (reader.Read()) {
result = Convert.ToInt32(reader["ShopperID"]);
}
}
}
return result;
}
First, it appears you close your connection, however you don't have an explicit open connection (unless you didn't include that line by mistake) which on a postback your query won't produce results since the connection is closed after you run it the first time. Second, confirm you don't have your code in a !Page.IsPostBack, which could also cause it not to appear. Finally you can do all that you are trying to do using one datareader instead of opening up two datareaders with this:
string strEmail = txtEmail.Text.ToLower();
string strPwd = txtPwd.Text.Trim();
string conString = ConfigurationManager.ConnectionStrings["YourConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("SELECT ShopperID, Name FROM Shopper WHERE Email = #Email AND Passwrd = #Passwrd", con))
{
con.Open();
cmd.Parameters.AddWithValue("#Email", strEmail);
cmd.Parameters.AddWithValue("#user_name", strPwd);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows)
{
if(dr["ShopperID"].ToString() != Session["ShopperID"].ToString())
{
Response.Redirect("~/default.aspx");
}
else if (dr["ShopperID"].ToString() == Session["ShopperID"].ToString())
{
lblWelcome.Text = "Welcome " + dr["Name"].ToString();
}
else
{
lblMsg.Text = "Incorrect email or password";
lblMsg.ForeColor = System.Drawing.Color.Red;
}
}
}
con.Close();
}
}
This also addresses the SQL injection by using Type-Safe SQL Parameters, which was outlined as an issue in other comments.

SqlException was unhandled by user code error, but information still being stored on database

So i'm using Visual Studio to create a asp.net web app in c# and I need some help regarding databases. I have a registration form that is filled out and depending on which radio button is selected, the information is stored in one of two tables. The issue I am having is when I hit the submit button on my app to store the data, it throws up an error message. The curious part is, the information still stores in the table even though I get the error message.
Can anyone help explain? I've attached pictures showing my code/error message and my tables. Thanks!
EDIT - This is my latest issue, posted from below:
After tweaking with some stuff, I am not getting the error message anymore. Now, the parent radio button is working (storing the info in parent table), but the child radio button is not. (nothing is being sent to the children table.
So after commenting out the 'if (parentRadBtn.Checked)' section so that the 'if (child.RadBtn.Checked)' section is first, information gets stored for children when running the app. So it seems there is an issue with my if statements and the program not reaching the 'if (child.RadBtn.Checked)' part. I have tried making it an 'if else' and various other things but none of them work. Can anyone spot what needs to be changed for the program to run through the children part? Thanks.
Tables
Code/error message
**Updated code**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace Coursework
{
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
successLabel.Text = ("Your submission is now being stored in our database");
}
}
protected void parentRadBtn_CheckedChanged(object sender, EventArgs e)
{
if (parentRadBtn.Checked)
{
firstNameBox.Text = string.Empty;
surnameBox.Text = string.Empty;
dayDobList.Text = string.Empty;
monthDobList.Text = string.Empty;
yearDobList.Text = string.Empty;
genderList.Text = string.Empty;
postcodeBox.Text = string.Empty;
teleBox.Text = string.Empty;
emailBox.Text = string.Empty;
userBox.Text = string.Empty;
passwordBox.Text = string.Empty;
genderList.Enabled = false;
dayDobList.Enabled = false;
monthDobList.Enabled = false;
yearDobList.Enabled = false;
surnameBox.Enabled = true;
postcodeBox.Enabled = true;
teleBox.Enabled = true;
emailBox.Enabled = true;
successLabel.Text = ("");
}
}
protected void passwordBox_TextChanged(object sender, EventArgs e)
{
}
protected void childRadBtn_CheckedChanged(object sender, EventArgs e)
{
else if (childRadBtn.Checked)
{
firstNameBox.Text = string.Empty;
surnameBox.Text = string.Empty;
dayDobList.Text = string.Empty;
monthDobList.Text = string.Empty;
yearDobList.Text = string.Empty;
genderList.Text = string.Empty;
postcodeBox.Text = string.Empty;
teleBox.Text = string.Empty;
emailBox.Text = string.Empty;
userBox.Text = string.Empty;
passwordBox.Text = string.Empty;
genderList.Enabled = true;
dayDobList.Enabled = true;
monthDobList.Enabled = true;
yearDobList.Enabled = true;
surnameBox.Enabled = false;
postcodeBox.Enabled = false;
teleBox.Enabled = false;
emailBox.Enabled = false;
successLabel.Text = ("");
}
}
protected void submitBtn_Click(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection("Data Source=THEBEAST;Initial Catalog=newregDB;Integrated Security=True;Pooling=False");
{
if (parentRadBtn.Checked)
{
SqlCommand pa = new SqlCommand("INSERT INTO parent(parentID, firstname, surname, postcode, telephone, email, password) VALUES (#parentID, #firstname, #surname, #postcode, #telephone, #email, #password)", connect);
pa.Parameters.AddWithValue("#parentID", userBox.Text);
pa.Parameters.AddWithValue("#firstname", firstNameBox.Text);
pa.Parameters.AddWithValue("#surname", surnameBox.Text);
pa.Parameters.AddWithValue("#postcode", postcodeBox.Text);
pa.Parameters.AddWithValue("#telephone", teleBox.Text);
pa.Parameters.AddWithValue("#email", emailBox.Text);
pa.Parameters.AddWithValue("#password", passwordBox.Text);
connect.Open();
pa.ExecuteNonQuery();
connect.Close();
if (IsPostBack)
{
userBox.Text = "";
firstNameBox.Text = "";
surnameBox.Text = "";
postcodeBox.Text = "";
teleBox.Text = "";
emailBox.Text = "";
passwordBox.Text = "";
}
else if (childRadBtn.Checked)
{
SqlCommand ca = new SqlCommand("INSERT INTO children(childID, firstname, dob, gender, password) VALUES (#childID, #firstname, #dob, #gender, #password)", connect);
ca.Parameters.AddWithValue("#childID", userBox.Text);
ca.Parameters.AddWithValue("#firstname", firstNameBox.Text);
ca.Parameters.AddWithValue("#dob", dayDobList.Text + monthDobList.Text + yearDobList.Text);
ca.Parameters.AddWithValue("#gender", genderList.Text);
ca.Parameters.AddWithValue("#password", passwordBox.Text);
connect.Open();
ca.ExecuteNonQuery();
connect.Close();
if (IsPostBack)
{
userBox.Text = "";
firstNameBox.Text = "";
dayDobList.Text = "";
monthDobList.Text = "";
yearDobList.Text = "";
genderList.Text = "";
passwordBox.Text = "";
}
}
}
}
}
}
}
Step through your code checking the value of userBox.Text prior to executing the query. Column childID is the only one that can cause this error, and the database is reporting that it is 0 (or is that () meaning empty string?).
You can also try manually deleting the record each time you run your code - you should no longer get the error.
Additional changes you might want to consider:
Add a constraint disallowing empty string as a legal childID value;
Name all your constraints, including the primary key constraint (PK_children is more readable than what you are getting);
Hope this helps.

How to display the correct amount of records for a chart in visual studios c#

Hello all just an update, I am still facing the issues of getting the chart to display the correct number of records. I have discovered where the chart is currently getting it's numbers from however it makes no sense as to why it is using those numbers. It is from a column in the database called "mpm_code" however I have never specified for the chart to use those numbers. Here are the numbers in the database:
Here is the chart
And here is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace RRAS
{
public partial class formRRAS : Form
{
public OleDbConnection DataConnection = new OleDbConnection();
string cmbRFR_item;
public formRRAS()
{
InitializeComponent();
}
//When the form loads it sets the intial combo box RFR item to null
private void formRRAS_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'database1DataSet.tblReject_test' table. You can move, or remove it, as needed.
this.tblReject_testTableAdapter.Fill(this.database1DataSet.tblReject_test);
cmbRFR.SelectedItem = "";
this.AcceptButton = btnSearch;
}
//AddRFR method, called in the NewRFRPopup
public void AddRFR(object item)
{
cmbRFR.Items.Add(item);
}
private void change_cmbSubRFR_items()
{
cmbSubRFR.Items.Clear();//Clear all items in cmbSubRFR comboBox.
switch (cmbRFR_item)//Adding your new items to cmbSubRFR.
{
case "":
cmbSubRFR.Items.Add("");
cmbSubRFR.Text = "";
break;
case "POSITIONING":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Anatomy cut-off");
cmbSubRFR.Items.Add("Rotation");
cmbSubRFR.Items.Add("Obstructed view");
cmbSubRFR.Items.Add("Tube or grid centering");
cmbSubRFR.Items.Add("Motion");
cmbSubRFR.Text = "";
break;
case "ARTEFACT":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("ARTEFACT");
cmbSubRFR.Text = "ARTEFACT";
cmbSubRFR.Text = "";
break;
case "PATIENT ID":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Incorrect Patient");
cmbSubRFR.Items.Add("Incorrect Study/Side");
cmbSubRFR.Items.Add("User Defined Error");
cmbSubRFR.Text = "";
break;
case "EXPOSURE ERROR":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Under Exposure");
cmbSubRFR.Items.Add("Over Exposure");
cmbSubRFR.Items.Add("Exposure Malfunction");
cmbSubRFR.Text = "";
break;
case "TEST IMAGES":
cmbSubRFR.Items.Add("");
cmbSubRFR.Items.Add("Quality Control");
cmbSubRFR.Items.Add("Service/Test");
cmbSubRFR.Text = "";
break;
}
}
private void cmbRFR_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbRFR_item != cmbRFR.SelectedItem.ToString())//This controls the changes in cmbRFR about selected item and call change_cmbSubRFR_items()
{
cmbRFR_item = cmbRFR.SelectedItem.ToString();
change_cmbSubRFR_items();
}
}
//The code for the button that closes the application
private void btnSearch_Click(object sender, EventArgs e)
{
//This creates the String Publisher which grabs the information from the combo box on the form.
//Select and Dataconnection are also defined here.
string Department = String.IsNullOrEmpty(txtDepartment.Text) ? "%" : txtDepartment.Text;
string Start_Date = String.IsNullOrEmpty(txtStart.Text) ? "%" : txtStart.Text;
string End_Date = String.IsNullOrEmpty(txtEnd.Text) ? "%" : txtEnd.Text;
string Anatomy = String.IsNullOrEmpty(txtAnatomy.Text) ? "%" : txtAnatomy.Text;
string RFR = String.IsNullOrEmpty(cmbRFR.Text) ? "%" : cmbRFR.Text;
string Comment = String.IsNullOrEmpty(cmbSubRFR.Text) ? "%" : cmbSubRFR.Text;
string Select = "SELECT * FROM tblReject_test WHERE department_id LIKE '" + Department + "'" + "AND body_part_examined LIKE'" + Anatomy + "'" + "AND study_date LIKE'" + Start_Date + "'" + "AND study_date LIKE'" + End_Date + "'" + "AND reject_category LIKE'" + RFR + "'" + "AND reject_comment LIKE'" + Comment + "'";
//DataConnection connects to the database.
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
//The DataAdapter is the code that ensures both the data in the Select and DataConnection strings match.
OleDbDataAdapter rdDataAdapter = new OleDbDataAdapter(Select, DataConnection);
try
{
//It then clears the datagridview and loads the data that has been selected from the DataAdapter.
database1DataSet.tblReject_test.Clear();
rdDataAdapter.Fill(this.database1DataSet.tblReject_test);
}
catch (OleDbException exc)
{
System.Windows.Forms.MessageBox.Show(exc.Message);
}
} //End of Search button
//Temporary button thats loads the chart when clicked
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
int count = database1DataSet.Tables["tblReject_test"].Rows.Count;
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(*) as count, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader[count]);
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
} //end of load chart button
//These buttons are all from the file menu bar
//A simple button that closes the application
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
//This button loads the NewRFRPopup form
private void addRFRToolStripMenuItem_Click(object sender, EventArgs e)
{
NewRFRPopup popup = new NewRFRPopup(this);
popup.ShowDialog();
}
private void printChartToolStripMenuItem_Click(object sender, EventArgs e)
{
charRejections.Printing.PrintDocument.DefaultPageSettings.Landscape = true;
charRejections.Printing.PrintPreview();
}
//End of file menu bar
//These buttons change the format of the chart
private void btnPie_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Pie;
}
private void btnBar_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Column;
}
private void btnSideways_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Bar;
}
private void btnLine_Click(object sender, EventArgs e)
{
this.charRejections.Series["RFR"].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line;
}
//end of chart formatting
}
}
The Issue has been sorted thanks to a friend of mine. This relates to the code that TaW posted the other day. Thanks for everyone's time and suggestions. The fixed code is below:
private void btnLoadChart_Click(object sender, EventArgs e)
{
charRejections.Series["RFR"].Points.Clear();
{
string connectiontring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\Database1.mdb";
DataConnection = new OleDbConnection(connectiontring);
try
{
DataConnection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = DataConnection;
string query = "SELECT COUNT(reject_category) as reject, reject_category FROM tblReject_test GROUP BY reject_category";
command.CommandText = query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
charRejections.Series["RFR"].Points.AddXY(reader["reject_category"].ToString(), reader["reject"].ToString());
}
DataConnection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}//end of load chart button

Session name is not retrieved in master page

i using a single master page in asp.net for log-In and Log-Out functionality...
but in master page session name takes null value.
Here is my code ,please help me...
MasterPage.master.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["name"] == null)
{
Panel2.Visible = false;
Panel1.Visible = true;
}
else if (Session["name"] != null)
{
Panel1.Visible = false;
Panel2.Visible = true;
Label2.Text = "WELCOME | Mr." + Session["name"].ToString();
}
}
}
protected void LoginStatus1_LoggedOut(object sender, EventArgs e)
{
Session.Clear();
Session.Abandon();
}
my homepage.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
string st="select Label4,Label3 FROM Register1_master WHERE Label4='" + TextBox1.Text + "' and Label3='" + TextBox2.Text + "'";
cmd = new SqlCommand(st, sqlcon);
cmd.Connection.Open();
string result= null;
Object value=cmd.ExecuteScalar ();
if ( value != null)
{
result = value.ToString ();
Session["name"] = TextBox1.Text;
Response.Redirect("Main.aspx");
}
else
{
Label3.Text="Invalid username or password";
}
cmd.Connection.Close();
}
after the login from homepage i'll be go on Main.aspx page
my Main.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HyperLink link = (HyperLink)Master.FindControl("HyperLink1");
link.Visible = false;
HyperLink link1 = (HyperLink)Master.FindControl("HyperLink2");
link1.Visible = true;
Label masterlbl = (Label)Master.FindControl("Label2");
string login = Convert.ToString(Session["name"]);
Session["name"] = login;
}
}
Have you try like this :
int result= null;
result= = Convert.ToInt32(cmd.ExecuteScalar());
Use the ExecuteScalar method to retrieve a single value (for example, an aggregate value) from a database. This requires less code than using the ExecuteReader method, and then performing the operations that you need to generate the single value using the data returned by a SqlDataReader.
A typical ExecuteScalar query can be formatted as in the following C# example:
cmd.CommandText = "SELECT COUNT(*) FROM dbo.region";
Int32 count = (Int32) cmd.ExecuteScalar();
Please refer MSDN

Refresh another forms DataGridView from button click

I have a form (customersForm) displaying a datagridview with customer information. And a second form (viewForm) which allows the user to view, edit,delete and update selected datagridview row. When I click update, or delete i'd like the datagridview on the customerForm to refresh displaying the updated data. How can I do this from a button click?
This is the viewForms complete code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace Lewis_Warby_Airbrushing
{
public partial class viewForm : Form
{
DataRowView Data = null;
public viewForm(DataRowView dr)
{
InitializeComponent();
Data = dr;
}
private void closeBTN_Click(object sender, EventArgs e)
{
this.Close();
}
private void viewForm_Load(object sender, EventArgs e)
{
refTxt.Text = Data["Reference"].ToString().Trim();
firstTxt.Text = Data["First Name"].ToString().Trim();
surenameTxt.Text = Data["Surename"].ToString().Trim();
address1Txt.Text = Data["Address Line 1"].ToString().Trim();
address2Txt.Text = Data["Address Line 2"].ToString().Trim();
countyTxt.Text = Data["County"].ToString().Trim();
postTxt.Text = Data["Post Code"].ToString().Trim();
contactTxt.Text = Data["Contact Number"].ToString().Trim();
emailTxt.Text = Data["Email Address"].ToString().Trim();
}
private void deleteBTN_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Customer information will be perminantly deteled. Do you with to continue? ", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = "delete from customersTBL where Reference ='" + this.refTxt.Text + "';";
SqlCeConnection conDataBase = new SqlCeConnection(constring);
SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase);
SqlCeDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Customer information has been deleted", "Deleted Sucessfully");
while (myReader.Read())
{
}
MessageBox.Show("Please exit the Customers window and re-open to update the table");
this.Close();
//displays a system error message if a problem is found
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void editBTN_Click(object sender, EventArgs e)
{
bool notEditable = true;
if (editBTN.Text == "Update")
{
int UserID = Convert.ToInt32(refTxt.Text);
UpdateDataBase( UserID );
editBTN.Text = "Edit";
deleteBTN.Visible = true;
notEditable = true;
}
else
{
deleteBTN.Visible = false;
editBTN.Text = "Update";
deleteBTN.Visible = false;
notEditable = false;
}
firstTxt.ReadOnly = notEditable;
surenameTxt.ReadOnly = notEditable;
address1Txt.ReadOnly = notEditable;
address2Txt.ReadOnly = notEditable;
countyTxt.ReadOnly = notEditable;
contactTxt.ReadOnly = notEditable;
emailTxt.ReadOnly = notEditable;
postTxt.ReadOnly = notEditable;
}
private void UpdateDataBase(int customerID)
{
if (MessageBox.Show("Customer information will be updated. This change cannot be undone. Are you sure you want to continue? ", "Confirm Edit", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
string constring = #"Data Source=|DataDirectory|\LWADataBase.sdf";
string Query = #"update customersTBL set [First Name] = #fname,
surename = #sur, [Address Line 1] = #addr1,
[Address Line 2] = #addr2, County = #county,
[Post Code] = #pcode, [Email Address] = #mail, [Contact Number] = #ctNo
WHERE Reference = #id";
using (SqlCeConnection conDataBase = new SqlCeConnection(constring))
using (SqlCeCommand cmdDataBase = new SqlCeCommand(Query, conDataBase))
{
try
{
conDataBase.Open();
cmdDataBase.Parameters.AddWithValue("#fname", this.firstTxt.Text);
cmdDataBase.Parameters.AddWithValue("#sur", this.surenameTxt.Text);
cmdDataBase.Parameters.AddWithValue("#addr1", this.address1Txt.Text);
cmdDataBase.Parameters.AddWithValue("#addr2", this.address2Txt.Text);
cmdDataBase.Parameters.AddWithValue("#county", this.countyTxt.Text);
cmdDataBase.Parameters.AddWithValue("#pcode", this.postTxt.Text);
cmdDataBase.Parameters.AddWithValue("#mail", this.emailTxt.Text);
cmdDataBase.Parameters.AddWithValue("#ctNo", this.contactTxt.Text);
cmdDataBase.Parameters.AddWithValue("#id", customerID);
int rowsUpdated = cmdDataBase.ExecuteNonQuery();
if (rowsUpdated == 0)
MessageBox.Show("No customer found to update");
MessageBox.Show("Customer information sucessfully updated", "Update Sucessfull");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
The complete code for customerForm:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace Lewis_Warby_Airbrushing
{
public partial class customerForm : Form
{
public customerForm()
{
InitializeComponent();
}
public void customerForm_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'lWADataBaseDataSet.customersTBL' table. You can move, or remove it, as needed.
timer1.Start();
this.lWADataBaseDataSet.EnforceConstraints = false;
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}
private void viewBTN_Click(object sender, EventArgs e)
{
int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];
viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
frm2.ShowDialog();
}
addForm addForm = new addForm();
private void addBTN_Click(object sender, EventArgs e)
{
if (addForm == null || addForm.IsDisposed == true)
addForm = new addForm();
addForm.ShowDialog();
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}
int count = 0;
private void timer1_Tick(object sender, EventArgs e)
{
count = customersTBLBindingSource.Count;
statusLBL.Text = "You currently have "+count.ToString()+" customer(s) stored in this database";
}
searchForm searchForm = new searchForm();
private void searchBTN_Click(object sender, EventArgs e)
{
if (searchForm == null || searchForm.IsDisposed == true);
searchForm = new searchForm();
searchForm.ShowDialog();
}
}
}
There is a lot you don't specify in your question, but let's assume this scenario:
When customerView is shown, you call the database to fill a DataGridView with customer details. At some point you either dbl-click on a DGV row, or you select a row and click a button, and then show viewForm, passing in the data in the currently selected row. Again, you don't specify how this is done, but let's assume you pass in a Data Transfer Object of some kind.
Once done editing, you click a button, save the changes to the database, then close viewForm.
According to your comments this is the general workflow you have in your application now.
In this case, you can simply re-fetch the data, as you did when first showing customerView when the viewForm.ShowDialog() method returns.
Unless there is something else I don't get, this can be easily done like this:
//customerForm
private void button1_Click(object sender, EventArgs e)
{
ViewFormClass viewForm = new ViewFormClass();
viewForm.SetCustomerData(dataObject);
viewForm.ShowDialog(); // will stop here waiting for viewForm to close
this.FetchCustomerData();
}
where FetchCustomerData() is the same method you called when opening customerView. In there you would typically fetch the data and bind it to controls.
Cheers
EDIT:
As per your own code, with a simple modification:
private void viewBTN_Click(object sender, EventArgs e)
{
int selectedRowIndex = customersTBLDataGridView.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = customersTBLDataGridView.Rows[selectedRowIndex];
viewForm frm2 = new viewForm((DataRowView)selectedRow.DataBoundItem);
frm2.ShowDialog();
this.customersTBLTableAdapter.Fill(this.lWADataBaseDataSet.customersTBL);
}

Categories