Saving to database, then reading from database, data is not there - c#

I have this page, where the user can modify it's information. When the page loads, it fills in the users information into the text input fields. You can then change your information and hit save. The data should be saved to the database and that should also be reflected in the text fields, because of the refresh. But it does not save the data. If I remove the reading of the data, the data is saved when the button is clicked, but when the data reading is there, the data is not saved.
This is the code in the "read the data" part, this is in the Page_Load():
string loggedInUser = System.Web.HttpContext.Current.User.Identity.Name;
SqlConnection ConnectDb = new SqlConnection("Data Source=serverHere;Initial Catalog=catalogHere;User ID=userNameHere;Password=passwordHere;"); //Opretter database connection string
SqlDataReader infoReader = null;
SqlCommand getUserInfo = new SqlCommand("SELECT firstName,lastName,age,city,contact,bio FROM UserInfo WHERE userName = #userName", ConnectDb);
getUserInfo.Parameters.Add("#userName", loggedInUser);
ConnectDb.Open();
infoReader = getUserInfo.ExecuteReader();
infoReader.Read();
{
tbInfoFirstName.Text = infoReader["firstName"].ToString();
tbInfoLastname.Text = infoReader["lastName"].ToString();
tbInfoAge.Text = infoReader["age"].ToString();
tbInfoCity.Text = infoReader["city"].ToString();
tbInfoKontakt.Text = infoReader["contact"].ToString();
tbInfoAbout.Text = infoReader["bio"].ToString();
};
ConnectDb.Close();
This is the code for the save button:
string loggedInUser = System.Web.HttpContext.Current.User.Identity.Name;
SqlConnection ConnectDb = new SqlConnection("Data Source=serverHere;Initial Catalog=catalogHere;User ID=userNameHere;Password=passwordHere;");
SqlCommand SavePersonInfo = new SqlCommand("UPDATE UserInfo SET firstName = #firstName,lastName = #lastName,age = #age,city = #city,contact = #contact,bio = #bio WHERE userName = #userName", ConnectDb);
SavePersonInfo.Parameters.AddWithValue("#firstName", tbInfoFirstName.Text);
SavePersonInfo.Parameters.AddWithValue("#lastName", tbInfoLastname.Text);
SavePersonInfo.Parameters.AddWithValue("#age", tbInfoAge.Text);
SavePersonInfo.Parameters.AddWithValue("#city", tbInfoCity.Text);
SavePersonInfo.Parameters.AddWithValue("#contact", tbInfoKontakt.Text);
SavePersonInfo.Parameters.AddWithValue("#bio", tbInfoAbout.Text);
SavePersonInfo.Parameters.AddWithValue("#userName", loggedInUser);
ConnectDb.Open();
SavePersonInfo.ExecuteNonQuery();
//Response.Redirect("Manage.aspx");
ConnectDb.Close();
As said, the save code works on it's own, but not when the reading code is also active, eg: Not commented out.

I believe that the Page_Load event is launched before the event button on PostBack.
In this case the reading taken are the old data again filling the fields and finally recording the old data again.
Have you checked it?
If so, put your code in Page_Load in an if (IsPostBack!):
public void Page_Load() {
// ...
if (!IsPostBack) {
// code read the data
}
}

Related

Compare a value in a table in SQL to an entry in a textbox

I have a table EmployeeRank1 in SQL Server that has a column Name. Under column Name there are two pre-defined names of employees. Moreover, in the table there is a column Password, which contains a generic password, which is "123456".
In WPF I have a textbox and that asks for name and one password box that asks for password. Underneath them, there is a button that says "Login".
The questions is how do I compare the content of Name and Pasword in my table to the input in the text box and the password box?
If the Name entered exists and the Password is correct, a new WPF page will be opened. Otherwise, a message stating that either the name or the password is incorrect will be printed.
This is what I have until now:
// check if the input matches and open the new WPF Page
private void EmployeeRank1Button_Click(object sender, RoutedEventArgs e)
{
try
{
// create a query and select everything from the EmployeeRank1 table
string query = "select * from EmployeeRank1";
// create a connection to the database and run the query
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(query, sqlConnection);
// use the sqlDataAdapter
using(sqlDataAdapter)
{
// create a new DataTable that allows us
// to store data from tables within objects
DataTable employeeRank1Table = new DataTable();
// fill the sqlDataAdapter with all the
// information from the query(from the employeeRank1Table)
sqlDataAdapter.Fill(employeeRank1Table);
// TODO: compare Name and Password entered in the TextBox and PasswordBox to the data in the table
if (tbName.Text == *Name in Table* && pbPassword.Password == *Password in Table*)
{
EmployeeRank1 employeeRank1 = new EmployeeRank1();
employeeRank1.Show();
}
}
}
catch(Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
You don't need to retrieve the whole table in memory. Just use a WHERE statement in your sql command with Name = #nameparam AND Password = #passparam, use an SqlCommand to retrieve a SqlDataReader and if the reader has a row, then bingo, the user exists.
Said that, remember that storing passwords in clear text is a big NO NO in a security concerned application. See this q/a for the reasons
private void EmployeeRank1Button_Click(object sender, RoutedEventArgs e)
{
try
{
// create a query and select just the record we need
string query = "select * from EmployeeRank1 where Name = #name AND Password = #pass";
// A local sqlconnection in a using statement ensure proper disposal at the end of this code
using SqlConnection con = new SqlConnection(connectionstring);
con.Open();
// Let's the database do the work to search for the password and name pair
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = tbName.Text ;
cmd.Parameters.Add("#pass", SqlDbType.NVarChar).Value = tbPassword.Text ;
SqlDataReader reader = cmd.ExecuteReader();
// If the reader has rows then the user/pass exists in the db table
if(reader.HasRows)
{
EmployeeRank1 employeeRank1 = new EmployeeRank1();
employeeRank1.Show();
}
}
catch(Exception exception)
{
MessageBox.Show(exception.ToString());
}
}
Note also that I used a local SqlConnection and not a global one inside a using statement. This is the correct way to use a Disposable object like a connection. Keeping a global connection is prone to resource leaks and all sorts of problems if something fails.

Auto retrieval of data in textbox

I have a log in page shown below
Admin only has a permission to access this page and he creates a new user with the following requirements.
when the particular user login his page is shown below
I need to retrieve the Faculty id,so that it should me automatically displayed in the textbox.
for that i need to call from datbase.? or is there any text box property to display the data ?
I am using asp.net withc#
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
textBox.Text = Comm1.ExecuteScalar();
Conn.Close();

how to reference to a fileupload control in a dataset

In my program, when user wants to edit a record, and presses Edit button, a new window opens up with all the fields and record information is rendered into the respective fields giving user an option to edit any field information they require.
I have added a fileupload control to my webform fields. But I am not sure how to reference fileupload control on my new popped up window .. I am not sure if I am explaining my problem very clearly or not but I will try to explain it with the help of following code:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
lblSet.Text = GridView1.Rows[e.NewEditIndex].Cells[2].Text;
MultiView1.SetActiveView(vRecord);
btnSave.Visible = false;
btnBacktoHome.Visible = true;
//this.lblMedium.Text = GridView1.Rows[e.NewEditIndex].Cells[1].Text;
using (SqlConnection con = new SqlConnection("Data Source=MEHDI-PC\\SQLEXPRESS;Initial Catalog=PIMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
String sql = "select [DocumentID],[Ref],[Subject],[Src],[Dst],[Medium],[Date_Printed],[Date_Received],[Document_Type],[Action_Required],[Due_Date],[Actual_Date],[Content],[Tag],[Issue_No],[Attachment],[Notes],[Assigned_To],[Reply_Ref],[Priority],[Status],[Response],[Physical_File_No],[Physical_Rack_Location] from dbo.Documents1 where [DocumentId]=N'" + GridView1.Rows[e.NewEditIndex].Cells[2].Text + "'";
cmd.Connection = con;
cmd.CommandText = sql;
con.Open();
//SqlDataAdapter da = new SqlDataAdapter(sql,con);
//DataTable dt = new DataTable();
DataSet ds = new DataSet();
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(ds);
}
this.txtRef.Text = ds.Tables[0].Rows[0][1].ToString();
this.txtSubject.Text = ds.Tables[0].Rows[0][2].ToString();
this.ddlSource.Text = ds.Tables[0].Rows[0][3].ToString();
this.ddlDestination.Text = ds.Tables[0].Rows[0][4].ToString();
this.ddlMedium.Text = ds.Tables[0].Rows[0][5].ToString();
this.txtDatePrinted.Text = ds.Tables[0].Rows[0][6].ToString();
this.txtDateReceived.Text = ds.Tables[0].Rows[0][7].ToString();
this.ddlDocumentType.Text = ds.Tables[0].Rows[0][8].ToString();
this.cbxAction.Checked = ds.Tables[0].Rows[0][9].Equals(cbxAction.Checked);
this.txtDueDate.Text = ds.Tables[0].Rows[0][10].ToString();
this.txtActualDate.Text = ds.Tables[0].Rows[0][11].ToString();
this.txtContent.Text = ds.Tables[0].Rows[0][12].ToString();
this.txtTag.Text = ds.Tables[0].Rows[0][13].ToString();
this.txtIssue.Text = ds.Tables[0].Rows[0][14].ToString();
//this.fileupload1 = ds.Tables[0].Rows[0][15] ;
this.txtNotes.Text = ds.Tables[0].Rows[0][16].ToString();
this.ddlAssignedTo.Text = ds.Tables[0].Rows[0][17].ToString();
this.txtReplyRef.Text = ds.Tables[0].Rows[0][18].ToString();
this.ddlPriority.Text = ds.Tables[0].Rows[0][19].ToString();
this.ddlStatus.Text = ds.Tables[0].Rows[0][20].ToString();
this.ddlResponse.Text = ds.Tables[0].Rows[0][21].ToString();
this.txtPhysicalFileNo.Text = ds.Tables[0].Rows[0][22].ToString();
this.txtPhysicalRackLocation.Text = ds.Tables[0].Rows[0][23].ToString();
if (con != null)
{
con.Close();
}
btnUpdate.Visible = true;
btnSearch.Visible = false;
BindGrid();
}
}
}
Basically when user clicks edit, what my code does is, reads the relevant record in the sql server and loads it from there to a new popped up window in my webform .. puts all the information in the related fields.
I read online that reading varbinary data from sql and binding it into the webform is not as simple as calling text data. (maybe I am wrong, please correct me if i am). I am not really worried about fetching data from sql server into the webform, I am worried about referring to the upload control in the new window because if user add a new file in fileupload control in the popped up window and if its not referenced in my code, my program ignores the new uploaded file which is a big flaw in my code.
Problem is with this line of code:
//this.fileupload1 = ds.Tables[0].Rows[0][15] ;
I have commented it out for other code to run.
I am stuck with it for a whole week. Any help will be so much appreciated. Thanks in advance.
You can't bind a record to a file upload control, this control is for uploading files
not
downloading.
Have a look at this link for how to download files.
The upload control should be used to replace the existing file,when the user chooses to replace it i.e. the user will upload a new file and in your business logic you need to update this record using the existing record ID.
In your case I'd bind the ID of the attachment to a hidden field in the grid and leave the upload control alone. When the record is updated check if the file upload control has a file and then using the value of the attachment update the attachment.
Edit: From here I believe you would need to add something along the lines of:
FileUpload file = ((FileUpload)(GridView1.Rows[e.NewEditIndex].FindControl("myFileUploadControl")));
You need to give your file upload control an ID of myFileUploadControl (or whatever you want)
This question also discusses using a fileupload control in a gridview.

populating a text box with lloyalty points from a access database;

Im trying to populate a text box with infromation that is searched by using a customerID which is inputted throught a text box here is the code im using below
private void txtCustomerID_TextChanged(object sender, EventArgs e)
{
string strCon = Properties.Settings.Default.PID2dbConnectionString;
OleDbConnection conn = new OleDbConnection(strCon);
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
txtPoints.Text = sqlPoints;
}
but the text box "txtPoints" only outputs the text of the sqlpoints and not the information in the database? I'm not exactly sure what im doing wrong here.
Any help is appreciated, thanks in advance.
You are not executing the SQL statement on the database. Instead, you are assigning it to txtPoints.Text. You need to execute it on the DB server using, e.g., an OleDbCommand object.
What you need to do instead is something like the following (note this is pseudo-code - I haven't tested it runs)
using (OleDbConnection conn = new OleDbConnection(strCon))
{
String sqlPoints = "SELECT points FROM customer WHERE [customerID]=" + txtCustomerID.Text;
// Create a command to use to call the database.
OleDbCommand command = new OleDbCommand(sqlPoints, conn)
// Create a reader containing your results
using(OleDbReader reader = command.ExecuteReader())
{
reader.Read(); // Advance to the first row.
txtPoints.Text = reader[0].ToString(); // Read the contents of the first column
}
}
Note also my use of using. This will ensure that your database connections are properly closed once you are finished with them.

Values added in the GridView are not saved in the database

Here is my following code:
string csr = "connection string";
string add = "Insert INTO table (Column1,Column2,Column3) Values (#Column1,#Column2,#Column3)";
using(SqlConnection connect = new SqlConnection(csr))
{
using ( SqlCommand command = new SqlCommand(add,connect))
{
command.Parameters.AddWithValue("Column1",textbox1.text");
//and so on
connect.Open();
command.ExecuteReader();
connect.Close();
}
}
I can see the data added in the gridview but when I check the table data in c# is empty, no value added. what's wrong?
You shouldn't have the connect.Close();, the using statement will take care of that for you.
command.Parameters.AddWithValue("Column1",textbox1.text")
should be
command.Parameters.AddWithValue("Column1",textbox1.text)
Set a breakpoint and ensure your connectionstring was properly set, textbox has a value, etc...

Categories