Values not updates after update query - sql

I am developing a project in ASP.NET with c# and SQL Server 2005 as back end. It includes a page profile.aspx which displays the information of a user from database. The session variable is used to keep track of the current logged in user.
The profiles table in the database contains a username column and 10 others columns like dept, address, contact, skills, interests etc etc.
I am displaying all these values on profile.aspx. Another page is edit_profile.aspx which comes up when the edit button on profile.aspx is clicked. Here the data is displayed in textboxes, with older entries already displayed, which can be edited, and click the Update button to confirm.
The update query runs fine, there is no error, but the values are not updates in the database tables. What is the possible reason? Solution?
Thank you
protected void Page_Load(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
protected void Button1_Click(object sender, EventArgs e)
{
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlCommand sda = new SqlCommand("update profiles set department='"+txt_deptt.Text+"',qualifications='"+txt_qualificatns.Text+"', address='"+txt_add.Text+"', contacts='"+txt_contacts.Text+"', interests='"+txt_interests.Text+"', awards='"+txt_awards.Text+"', website='"+txt_website.Text+"', skills='"+txt_skills.Text+"', mstatus='"+txt_mstatus.Text+"' where username='" + Session["currentusername"].ToString() + "'", con);
DataSet ds = new DataSet();
try
{
con.Open();
int temp=sda.ExecuteNonQuery();
con.Close();
if (temp >= 1)
{
lbl_message.ForeColor = System.Drawing.Color.Green;
lbl_message.Text = "Profile Updated Successfully!";
}
else
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Integer less than 1";
}
}
catch
{
lbl_message.ForeColor = System.Drawing.Color.Red;
lbl_message.Text = "Try Again Later, An Error Occured!";
}
//Response.Redirect("profile.aspx");
}
}

You are overwriting the contents of your textboxes every time the page loads so the user inputted conntet is never written to the database...
Look at the Page.IsPostBack method. Basically, wrap the commands to fill the textboxes with
if (!Page.IsPostBack) {}
To only load the values into the text box the first time the page loads (and so not overwrite the user entered values when you click the button you need to check that the page isn't a post back.
I think maybe a book on basic ASP.Net will help answer many questions you may have early on.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack) {
string CNS = ConfigurationManager.ConnectionStrings["myconn"].ToString();
SqlConnection con = new SqlConnection(#CNS);
SqlDataAdapter sda = new SqlDataAdapter("select * from profiles where username='" + Session["currentusername"].ToString()+"'", con);
DataSet ds = new DataSet();
sda.Fill(ds, "profiles");
txt_name.Text = ds.Tables["profiles"].Rows[0][0].ToString();
txt_deptt.Text = ds.Tables["profiles"].Rows[0][1].ToString();
txt_qualificatns.Text = ds.Tables["profiles"].Rows[0][2].ToString();
txt_add.Text = ds.Tables["profiles"].Rows[0][3].ToString();
txt_contacts.Text = ds.Tables["profiles"].Rows[0][4].ToString();
txt_interests.Text = ds.Tables["profiles"].Rows[0][5].ToString();
txt_awards.Text = ds.Tables["profiles"].Rows[0][6].ToString();
txt_website.Text = ds.Tables["profiles"].Rows[0][7].ToString();
txt_skills.Text = ds.Tables["profiles"].Rows[0][8].ToString();
txt_mstatus.Text = ds.Tables["profiles"].Rows[0][9].ToString();
ds.Reset();
}
}

Related

Passing DropDownList value into SQL command in ASP.net

I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
Command.Connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
DataTable dataTble1 = new DataTable();
dataAdapter.Fill(dataTble1);
if (dataTble1.Rows.Count > 0)
{
foreach (DataRow row in dataTble1.Rows)
{
ListItem course1 = new ListItem(row["Course"].ToString());
if (!DropDownList1.Items.Contains(course1))
{
DropDownList1.Items.Add(course1); // showing the 2 courses
}
}
}
Command.Connection.Close();
}
}
Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = #course", sqlConnection1);
Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem);
Command.Connection.Open();
SqlDataReader sqlDataReader1 = Command.ExecuteReader();
if (sqlDataReader1.Read())
{
LabelAverage.Text = sqlDataReader1[0].ToString();
}
else
{
LabelAverage.Text = "No Data"; // doesn't get into here anyhow
}
}
EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = #course" and Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem.Text), or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.
I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
Adding that to DropDownList solved the problem.
// query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
{
Label = s.Adi,
Value = s.ID.ToString()
}).ToList();

Login form in ASP.net does not work

I'm new to ASP.net and currently failing to create a simple functioning login form. After establishing the connection to my database, I wanted the function to check whether a given combination of username and password exists in the database. Due to the fact that I have not created the "member zone" page yet, It's supposed to do nothing if the data is valid and return "Login failed" in the opposite case. For some reason, it doesn't work. I would be glad if someone could help me trace the problem.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT * FROM users WHERE username='" + UserName.Text +
"' AND password='" + Password.Text + "' ";
SqlCommand cmd = new SqlCommand(query, con);
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
Response.Write("Login failed.");
}
You have SELECT * FROM in the query and you are using ExecuteScalar method to check if anything is returned.
You should use SELECT COUNT(*) FROM to get the number of rows exist in the table for given username and password.
Another thing which is not right in your code is the generation of query. Using parameterized query is the most recommended approach.
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}
This should resolve your issue.
You forgot to open connection before executing ExecuteScalar()
protected void Login_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connect"].ToString());
string query = "SELECT COUNT(*) FROM users WHERE username=#userName AND password=#password";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("#userName", UserName.Text));
cmd.Parameters.Add(new SqlParameter("#password", Password.Text));
//Add Below line and test your code.
con.Open();
string output = cmd.ExecuteScalar().ToString();
if (output == "1")
{
//Creating a session for the user
Session["user"] = UserName.Text;
Response.Redirect("");
}
else
{
Response.Write("Login failed.");
}

Manually Sorting Data in Gridview in asp.Net Webforms

I am having some difficult manually sorting data on a gridview. I used a dataset and when set the AllowSort to true and also wrote the code to handle the sort based on the guide given on https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx . However, when I run my code, the data displays but when I click the header of each column, nothing happens.
here is my code
protected void Page_Load(object sender, EventArgs e)
{
string connstring = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.CommandText = "SELECT Count(Student.StudentID) AS StdCount, Schools.Name, Schools.StartDate, School.SchoolFees FROM Schools INNER JOIN Students ON Schools.SchoolID = Student.SchoolID WHERE School.Active = 1 GROUP BY Schools.Name, Schools.StartDate, Schools.SchoolFess ORDER BY Schools.Name ASC";
SqlDataAdapter da = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
ViewState["datable"] = dt;
}
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)ViewState["datable"];
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = ViewState["datable"];
GridView1.DataBind();
}
}
private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";
// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;
if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
// Save new values in ViewState.
ViewState["SortDirection"] = sortDirection;
ViewState["SortExpression"] = column;
return sortDirection;
}
Any help will be appreciated. Thanks
You need to bind the DefaultView of the DataTable, which is this orderly, not ViewState variable.
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)ViewState["datable"];
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
}
}
This looks to be a Page LifeCycle issue.
Every time you post back the entire Page LifeCycle runs
In your case you are retrieving and overwriting ViewState["datable"] on every postback, assuming of course that if (ds.Tables.Count > 0) evaluates to true.
And then you do this in Page Load:
GridView1.DataSource = ds;
but in your sorting routine you access:
DataTable dt = (DataTable)ViewState["datable"];
...
GridView1.DataSource = ViewState["datable"];
You just replaced GridView.DataSource, which initially was a DataSet, with a DataTable
Wrap your initial data Retrieval in PageLoad like this
if( !Page.IsPostback )
{
// This retrieves Data once, and you persist it
// in the ViewState no need to Keep retrieving it
// unless the data has changed
}
// Rebind outside the if
GridView1.DataSource = (DataTable) ViewState["datable"];
GridView1.DataBind();
Addendum
Per Andrei he is correct. ViewState is a hidden field on your rendered ASPX. View the page source in your browser and search for
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="" />
It's Ok to use as a learning aid as long as the dataset is small and doesn't contain any confidential information.
But as it's transmitted to and from your page on every postback you incur a lot of overhead. Imagine if your DataSet contained several thousand rows.
Session State is a better option, but the Application Cache is better still. Server Data Controls like SqlDataSource make use of this cache and so can you. Access it just like ViewState:
ViewState["datable"] = dt;
Cache["datable"] = dt;
But don't go crazy with it. ViewState, SessionState, Cookies, LocalStorage, etc all have their place, learn them.

Why SQL will only update the text boxes original text? ASP.Net

so the problem I'm having is that on my button click it's supposed to update the database with the values in the text boxes. These are being read in on the page load. Having modified the code a bit to see what's going on, even if the content of the text box is changed, it submits the original text. I can't wrap my head around why. I need it to submit any changes to those text boxes. Any help or guidance appreciated.
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string checkic1 = "SELECT colum1 FROM table1 WHERE ID='1';";
SqlCommand c1Comm = new SqlCommand(checkic1, con);
string ic1 = c1Comm.ExecuteScalar().ToString();
con.Close();
c1TxtBox.Text = ic1;
}
The example above is the same for c2TxtBox and c3TxtBox as well.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection update = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
string addUpdate= "UPDATE table1 SET colum1 = #c1, colum2 = #c2, colum3 = #c3 WHERE ID='1';";
SqlCommand comA = new SqlCommand(addUpdate, update);
comA.Parameters.AddWithValue("#c1", c1TxtBox.Text);
comA.Parameters.AddWithValue("#c2", c2TxtBox.Text);
comA.Parameters.AddWithValue("#c3", c3TxtBox.Text);
update.Open();
comA.ExecuteNonQuery();
update.Close();
Response.Redirect("originalPage.aspx");
}
}
The PageLoad function is called everytime you load the page, also when you submit the page by clicking your button. Therefore, the value of the textbox is overwritten before you try to update your database (because PageLoad is called before Button1_Click).
To overcome this, you could add a check to see if you are currently in a post back in your PageLoad method, like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
string checkic1 = "SELECT colum1 FROM table1 WHERE ID='1';";
SqlCommand c1Comm = new SqlCommand(checkic1, con);
string ic1 = c1Comm.ExecuteScalar().ToString();
con.Close();
c1TxtBox.Text = ic1;
}
}

Simple textbox connected with button, SQL

I need to make complicated form which includes textboxes and buttons. But I would like to learn how to do in on simple example. I am connecting to local SQL server with application written in visual basic.
How can I make very simple form, for example with first name and last name and with submit button, which sends those data to database? Here is my code:
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection
("Server=[...];Initial Catalog=[...]);
}
Everything is fine with connection, but I need to insert data with textboxes and buttons.
Try Like this
private void button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Server=[...];Initial Catalog=[...]");
conn.Open();
string sql = "INSERT INTO User (firstname,lastname)VALUES(#fname,#lname)";
cmd.CommandText = sql;
cmd.Connection = conn;
cmd.Parameters.Add("#fname", SqlDbType.VarChar, 100);
cmd.Parameters["#fname"].Value = TextBox1.Text;
cmd.Parameters.Add("#lname", SqlDbType.VarChar, 100);
cmd.Parameters["#fname"].Value = TextBox2.Text;
cmd.ExecuteNonQuery();
}