How to Save the data in Page using C# - c#

I am working one portal where user can login and will enter his details and later he can view those details after login again. But unfortunately data is not not displaying in page. Here is I am giving everything which I did.
Code Explanation:
This is the Button code for data in database.
protected void btnContactInfoSave_click(object sender, EventArgs e)
{
if (chkContactUpdate.Checked)
{
string[] ContactInfoData = new string[6];
ContactInfoData[0] = GlobalVars.UserEmail;
ContactInfoData[1] = txtCnct.Text;
ContactInfoData[2] = txtAltCnct.Text;
ContactInfoData[3] = txtEmrCnct.Text;
ContactInfoData[4] = txtPrsnEmail.Text;
ContactInfoData[5] = txtOfsEmail.Text;
Utilities.sqlUploadContactInfoData(ContactInfoData);
}
else
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Error", "alert('Please click on the checkbox before Saving.');", true);
}
}
Here is the code for the Button creation :
When user clicks this button data should be added in database. wat ever the data user enters it has to save in database.
Code for uploading the data in database.
public static void sqlUploadContactInfoData(string[] Userdata) // code for saving the data in database
{
using (SqlConnection sqlConn = PortalDBConnection())
{
try
{
sqlConn.Open();
string spName = "sp_testSample";
SqlCommand cmd = new SqlCommand(spName, sqlConn);
cmd.Parameters.AddWithValue("#CnctNum", Userdata[1].ToString());
cmd.Parameters.AddWithValue("#AltCnctNum", Userdata[2].ToString());
cmd.Parameters.AddWithValue("#EmerCnctNum", Userdata[3].ToString());
cmd.Parameters.AddWithValue("#PrsnEmail", Userdata[4].ToString());
cmd.Parameters.AddWithValue("#OfsEmail", Userdata[5].ToString());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = sqlConn;
cmd.ExecuteNonQuery();
}
catch (SqlException)
{
ErrorMsg("Server Error", "Server Error ! Please try again Later.");
}
}
}
Here I have a problem that I am unable to display the data in page.
When user clicks the button, data is saving in database. The problem is when user login and fill the data and he can save the data. once he logged out from portal and after login again data is not displaying there. Data need to save in page also.
Any problem in above code..??

string strCnctNum = txtCnctNum.Text;
//Then reset your control like below
`txtCnctNum.Text = "";
txtAltCnctNum.Text = "";
...
etc
// Then Use This Code to To Retrieve & Display Data
using (SqlConnection oSqlConnection = new SqlConnection("YourConnectionString"))
{
string strCommand = "Select * from YourTableName where CnctNum="+ strCnctNum +";
SqlCommand oCmd = new SqlCommand(strCommand, oSqlConnection);
oSqlConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
txtCnctNum.Text = oReader["CnctNum"].ToString();
txtAltCnctNum.Text = oReader["AltCnct"].ToString();
.....
etc
}
oSqlConnection.Close();
}
}`

Related

Ticket Booking System: Database access issue

I'm creating a Bus Ticket booking system. I have created a database called traveller and two tables named Useriden and BusDB respectively. In the aspx.cs file(Sign Up page), I'm checking for duplicate usernames but it simply navigates to the next page
I've tried everything but I'm unable to resolve this issue. I'm not getting any errors or warnings.
protected void BtnConfirmSignup_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(localdb)\\MSSQLlocalDB;Initial Catalog=traveller;Integrated Security=True;Pooling=False");
SqlCommand cmd;
SqlDataReader read;
/*DEBUG: Prevent duplicate usernames*/
try
{
Session["user"] = TxtUsrName.Text;
Session["pass"] = TxtPsswd.Text;
Session["email"] = TxtEmail.Text;
cmd = new SqlCommand("select Name from Useriden",con);
con.Open();
read = cmd.ExecuteReader();
while (read.Read()) {
if ((read["Name"].ToString()).Equals(TxtUsrName.Text))
{
throw new Exception("Invalid Username");
}
else
{
Response.Redirect("SignUpNext.aspx");
}
}
}
catch (Exception ex) {
LabelUserName.Visible = true;
LabelUserName.Text = ex.Message;
con.Close();
ViewState["Caption"]=ex.Message;
}
}
On clicking the confirm button, it should check for duplicate usernames. I already have one record with the name "Faf" in my table Useriden. When I try to sign up using the same username, it's not throwing an exception instead it navigates to SignUp.aspx.
The duplicate check is only valid if there's one record. I'll modify the logic so that it works for more than record but right now, it's not even working for a single record.

Is it possible to create a ‘user account’ windows application without ASP.NET?

I am relatively new to C# and currently working on an 'Account' windows application. I did not use ASP.NET, just Winforms and a .mdf database. My main goal now is for the details of a user (from the database) to be displayed on the Home page right after I login.
For example:
Login Page
Username : sandy#mail.com
Password : 1234
Home Page
Welcome, Sandy Smith!
Your current address : Woodlands Drive
Here is the code for my Login button:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\sit\Desktop\25June_LessonEffectivenessAnalysis\LessonEffectivenessAnalysis\LessonEffectivenessAnalysis\LessonEffectivenessAnalysis\LessonAnalysis.mdf;Integrated Security=True");
SqlDataAdapter sda = new SqlDataAdapter("select count(*) from TBL_LOGIN where STAFF_EMAIL ='" + textBox1.Text + "' and PASSWORD='" + textBox2.Text + "'", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
this.Hide();
Home_Page hp = new Home_Page();
hp.Show();
}
else
{
MessageBox.Show("Please a valid email and password.", "alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Would greatly appreciate it if anyone could help. Thanks!
This is how i am doing it with winforms
In database create table USERS with columns USERID, PASS, DISPLAY_NAME, EMAIL, ANYTHING YOU WANT TO STORE FOR EACH USER....
Create new class (.cs file) and name it CurrentUser
Inside it create public static vars - Datatype which is accessible from anywhere in code (write/read) - for each column in database.
So class would look like this:
public class CurrentUser
{
public static int userId;
public static string pass;
public static string displayName;
public static string email;
//every other column you added
}
Now create login code like this
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\sit\Desktop\25June_LessonEffectivenessAnalysis\LessonEffectivenessAnalysis\LessonEffectivenessAnalysis\LessonEffectivenessAnalysis\LessonAnalysis.mdf;Integrated Security=True");
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("SELECT PASS, USERID, DISPLAY_NAME, FROM USERS WHERE EMAIL = #MAIL", conn)
{
cmd.Parameters.AddWithValue("#MAIL", textBox1.Text);
SqlDataReader dr = cmd.ExecuteReader():
if(dr.Read()) //We do IF since we only need first one
{
//Now we check if typed password is equal to password from database
if(dr[0].ToString().Equals(textBox2.Text))
{
this.Hide();
Home_Page hp = new Home_Page();
hp.Show();
//Here we store current user data
CurrentUser.userId = Convert.ToInt32(dr[1]);
CurrentUser.pass = dr[0].ToString();
CurrentUser.displayName = dr[2].ToString();
CurrentUser.email = textBox1.Text;
}
else //Passwords doesn't match
{
MessageBox.Show("Wrong password. Try again");
}
}
else //If it hasn't found anyone with that email that mean email is incorect
{
MessageBox.Show("E-mail doesn't exist!");
}
}
}
}
And now in whatever class/form you are (which is inside your namespace) you can access current user's data with let's say string displayName = CurrentUser.displayName.
Or if you want to set label with hello message you can do
label1.Text = "Welcome, " + CurrentUser.displayName + "!";
Or better
label1.Text = String.Format("Welcome, {0}!", CurrentUser.displayName);
Or if you want to display messageBox with all data just do
string[] msg = {
String.Format("Welcome, {0}.", CurrentUser.displayName),
String.Format("Your ID is: {0} while your e-mail is {1}!", CurrentUser.userId, CurrentUser.email)
};
MessageBox.Show(String.Joing(Environment.NewLine, msg));

Updating and retrieving images (Asp.net c#)

protected void upimg_about_Click(object sender, EventArgs e)
{
con.Open();
string sqlQuery = " UPDATE [dbo].[tbldetails] SET [image]=#image,[image2]=#image2 WHERE id=#id";
SqlCommand cmd2 = new SqlCommand(sqlQuery, con);
cmd2.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = Image1.PostedFile.ContentLength;
int img2 = Image2.PostedFile.ContentLength;
byte[] msdata = new byte[img];
byte[] msdata2 = new byte[img2];
Image1.PostedFile.InputStream.Read(msdata, 0, img);
Image2.PostedFile.InputStream.Read(msdata2, 0, img2);
cmd2.Parameters.AddWithValue("#image", msdata);
cmd2.Parameters.AddWithValue("#image2", msdata2);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
cmd2.ExecuteNonQuery();
con.Close();
data1.Text="Image Updated Successfully";
}
This is the code I am using to update the images in the database.
The user when required can update the images (eg: in the firstpage.aspx) and can retrieve it in the next page (nextpage.aspx).
But the problem is: suppose a user wants to update just a single image and he/she upload's the image and clicks the update button and when retrieving images in the next page the image that was updated is visible but the one which is already present in the database is not. I am not sure but during the updation the other fileupload is empty is this why this is happening? Is there other way to do it?
PS: I have textboxes in the firstpage.aspx in which i am retrieving the text he/she has already put in the database and hence when the user wants to make changes it can be done easily.
TextBox1.Text = dr["name"].ToString();
TextBox2.Text = dr["address"].ToString();
So, is it possible to retrieve the image path which the user has previously submitted? Or any way in which the user can update a single image and during retrieval both the images can be retrieved?
Thank You! :)
Break your code up so that you can send 1 image at a time to the DB. Then pass the corresponding FileUpload and SQL Column name to your function. Conditionally send the new file to the database depending on whether the FileUpload contains a file. You can check this by looking at the HasFile property.
protected void upimg_about_Click(object sender, EventArgs e)
{
// make sure at least 1 file
if (!Image1.HasFile && !Image2.HasFile)
{
data1.Text="No Images Uploaded";
return;
}
con.Open();
UploadImage(Image1, "[image]");
UploadImage(Image2, "[image2]");
con.Close();
data1.Text = "Image Updated Successfully";
}
void UploadImage(FileUpload fileUpload, string columnName)
{
if (!fileUpload.HasFile)
{
return;
}
string sqlQuery = "UPDATE [dbo].[tbldetails] SET " + columnName + "=#image WHERE id=#id";
SqlCommand cmd = new SqlCommand(sqlQuery, con);
cmd.Parameters.AddWithValue("#id", Session["email"].ToString());
int img = fileUpload.PostedFile.ContentLength;
byte[] msdata = new byte[img];
fileUpload.PostedFile.InputStream.Read(msdata, 0, img);
cmd.Parameters.AddWithValue("#image", msdata);
cmd.ExecuteNonQuery();
}

SQL query based on combobox selection

I am creating a database application and I'm having difficulty implementing a query. I have a query which populates a combobox with customer's bank accounts this is the code for the query:
private void ShowAccounts()
{
string sql = "SELECT account.custid, product.name FROM account INNER JOIN product ON account.prodid = product.prodid WHERE account.custid = #AccountID";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", customerData.CustomerID);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
comboAccounts.Items.Add(reader["name"].ToString());
}
}
}
This works the way I need it to but based on the account selection I need to display the account balance and I'm wondering how to go about writing that query. Any help would be appreciated.
Thank you
I guess this is what you are trying to do? I am guessing on your column and table names so you will need to modify the sql statement if I got it wrong.
private string Get_Balance(string AccountNumber)
{
string sql = "SELECT balance FROM account WHERE custid = #AccountID";
string balance = "";
using (OleDbConnection connection = new OleDbConnection(Properties.Settings.Default.ConnectionScring))
{
OleDbCommand command = new OleDbCommand(sql, connection);
command.Parameters.AddWithValue("#AccountID", AccountNumber);
connection.Open();
using (OleDbDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
balance = reader["balance"].ToString();
}
}
}
return (balance);
}
Use the SelectedIndexChanged event of your combo box to call the above code. You will need to add the event handler to the combo box (just double click it on the form and VS will do it for you).
private void comboAccounts_SelectedIndexChanged(object sender, EventArgs e)
{
if(comboAccounts.Text != "")
{
balanceLabel.text = Get_Balance(comboAccounts.text); //Or whatever you named the label you want your balance to to into.
}
}
After you populate your combo box with your code, whenever the combo box is dropped down and changed it will pass the text of whatever is in the combo box to Get_Balance which will return a string that will be placed in the label.

How to redirect login page to previous page in ASP.NET C#?

I'm new on ASP.NET. i am developing one jobportal website using asp.net C#. In website user after find their job post when try to click on "Apply Now" , if session empty, page will redirect to "CandidateLogin.aspx".
After login the page will redirect to last visited page, and then user can apply. If user open the website and open login page, or directly enter login page URL, after login it will redirect to Candidate Profile page. Any help would be appreciated.
protected void btnLogin_Click(object sender, EventArgs e)
{
string ConnString = System.Configuration.ConfigurationManager.ConnectionStrings["jobforu"].ToString();
SqlConnection conn = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand();
conn.Open();
cmd.Connection = conn;
cmd.Parameters.Clear();
SqlDataReader dr;
canname = "";
canpwd = "";
canemail = "";
session_canFirstName="";
cmd.CommandText = "select * from jobforu.dbo.can_master where can_email = #can_email and can_pwd = #can_pwd";
cmd.Parameters.AddWithValue("#can_email", txtEmail.Text.Trim());
cmd.Parameters.AddWithValue("#can_pwd", txtPassword.Text.Trim());
dr = cmd.ExecuteReader();
while (dr.Read())
{
canname = dr["can_fname"].ToString() +" "+ dr["can_mname"].ToString() +" "+ dr["can_lname"].ToString();
canpwd = dr["can_pwd"].ToString();
canemail = dr["can_email"].ToString();
session_canFirstName = dr["can_fname"].ToString();
sessionCanCode = dr["can_code"].ToString();
}
dr.Close();
conn.Close();
cmd.Parameters.Clear();
if (canname.Length > 1)
{
Session["canname"] = canname;
Session["canpwd"] = canpwd;
Session["canemail"] = canemail;
Session["sessionCanCode"] = sessionCanCode;
Response.Redirect(ViewState["GoBackTo"].ToString());
}
else
{
//Response.Write("Invalid user name or password");
lblErrorMsg.Visible = true;
lblErrorMsg.Text = "Invalid user name or password!";
txtEmail.Text = "";
txtPassword.Text = "";
txtEmail.Focus();
}
}
Page Load:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["sessionCanCode"] != null)
{
Response.Redirect("jobseekers/Default.aspx?ref=m_icon");
}
if (!Page.IsPostBack)
{
ViewState["GoBackTo"] = Request.UrlReferrer;
FillCapctha();
}
lblErrorMsg.Visible = false;
}
I am assuming you are using webforms. An you want to redirect after login to it's previous page. For that you can use the Request.UrlReferrerproperty. However this property will be null if the HTTP header value is not a URI or if the field was not set by the client UA.
You must never depend on this mechanism because it is set by the client, and you must never trust the client ( http://en.wikipedia.org/wiki/Defensive_programming ). And as stated, not all visitors will have the Referer header set.
Instead what you can do is use the Request.QueryString to pass the previous page URL to the LoginPage. ANd when user log's in use that URl to redirect back to the page.

Categories

Resources