Trying to update table in sql server but not working - c#

I am trying to update table in sql server but it's not working. Here is my code
SqlConnection conn;
string connString = ConfigurationManager.ConnectionStrings["Alumnidb"].ConnectionString;
string userName;
SqlCommand cmdProfile, cmdUpdate;
SqlDataReader reader;
string UserId;
protected void Page_Load(object sender, EventArgs e)
{
userName = Request.QueryString["UserName"].ToString();
RetriveProfile();
}
protected void RetriveProfile()
{
conn = new SqlConnection(connString);
cmdProfile = new SqlCommand("SELECT Name, UserId FROM UserProfile WHERE UserName=#UserName",conn);
cmdProfile.Parameters.AddWithValue("#UserName",userName);
conn.Open();
reader = cmdProfile.ExecuteReader();
while (reader.Read())
{
TextBoxName.Text = reader["Name"].ToString();
UserId = reader["UserId"].ToString();
}
conn.Close();
}
protected void buttonUpdate_Click(object sender, EventArgs e)
{
conn = new SqlConnection(connString);
cmdUpdate = new SqlCommand("UPDATE UserProfile SET Name=#Name WHERE UserId=#UserId",conn);
cmdUpdate.Parameters.AddWithValue("#UserId",UserId);
cmdUpdate.Parameters.AddWithValue("#Name",TextBoxName.Text.ToString());
conn.Open();
cmdUpdate.ExecuteScalar();
conn.Close();
}
and .aspx file
Name: <asp:TextBox ID="TextBoxName" runat="server" ></asp:TextBox>
<asp:Button ID="buttonUpdate" runat="server" Text="UpDate"
onclick="buttonUpdate_Click"/>
It shows me the previous value as before updated. . i checked in sql server and there is also no change in there
What am i doing wrong?
Your help will be appreciated. . .Thanx

The problem is that you fill all values in Page_Load even if you are in a postback. So if the user clicks on the update-button Page_Load is fired first, all values are loaded from database and you set the TextBox.Text value to the old value. So all changes are lost.
So use the IsPostBack property:
protected void Page_Load(object sender, EventArgs e)
{
userName = Request.QueryString["UserName"].ToString();
if(!IsPostBack)
RetriveProfile();
}
Since you are getting the UserID from the sql query and you need that in the update you have several options. You could persist the userid across postbacks e.g. in ViewState or Session. This can be done in RetriveProfile.
protected void RetriveProfile()
{
conn = new SqlConnection(connString);
cmdProfile = new SqlCommand("SELECT Name, UserId FROM UserProfile WHERE UserName=#UserName",conn);
cmdProfile.Parameters.AddWithValue("#UserName",userName);
conn.Open();
reader = cmdProfile.ExecuteReader();
while (reader.Read())
{
TextBoxName.Text = reader["Name"].ToString();
UserId = reader["UserId"].ToString();
}
conn.Close();
}
Change the field UserID to be a property:
private string UserId {
get { return (string)ViewState["UserID"]; }
set { ViewState["UserID"] = value;}
}
Note that all variables are disposed at the end of every page's lifecycle due to the statelessness of HTTP. Therefore you need to persist it somewhere.
Nine options for managing persistent User State in your ASP.NET Application

Related

How to get user input passed through to my query and display results in a label

I have another question posted where my query would not return the results into my sealresult Label. So I figured to ask it in a different way because I still cannot figure this out. I have the following code, it runs perfectly when the button "Search" is clicked and returns the query result. However, I have a textBox with an Id of receiptbox and I want to enable an user to input text and that be placed into the query to gather the result into the sealresult Label. How do I accomplish this? I want user input where it says RE00007544 from a textbox labeled receiptbox.
protected void receiptbox_TextChanged(object sender, EventArgs e)
{
}
protected void sealresultquery_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
protected void searchbutton_Click(object sender, EventArgs e)
{
sealresult.Text = "";
string connString = #"Data Source=SQL;Initial Catalog=mydatabase;User ID=admin;Password=******";
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = 'RE00007544'";
SqlConnection conn = new SqlConnection(connString);
SqlCommand comm = new SqlCommand(query, conn);
using (conn)
{
try
{
conn.Open();
SqlDataReader reader = comm.ExecuteReader();
while(reader.Read())
{
sealresult.Text += reader[0].ToString();
}
reader.Close();
}
catch(Exception ex)
{
querystatus.Text = ex.Message;
}
}
}
If I understand, I think the simplest modification to the code you provided would be:
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = '" + receiptbox.Text + "'";
However, it's not the most secure way. You shouldn't be this trusting with user input.
Learn to use parameters which will save you from sql injections.
Change your code like below.
string query = "Select seal1 from dbo.RECEIPTHEADER where receipt = #number";
//define parameters used in command object
SqlParameter param = new SqlParameter();
param.ParameterName = "#number";
param.Value = receiptbox.Text.Trim();
//add new parameter to command object
comm.Parameters.Add(param);

search an item by name and display the content in another page

I want to display an item information in gridview from data base by using it name , and i want the gridview to be in another page
i tried this code,,but it didn't work
in the first page
protected void Page_Load(object sender, EventArgs e)
{
}
public string txt
{
get
{
// Return the actual name if it is not null.
return TextBox1.Text ?? string.Empty;
}
}
}
in the second page
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source=FATIMAH;Initial Catalog=makeup;Integrated Security=True");
string find = "select * from product where(name like '%' +#name+ '%')";
SqlCommand comm = new SqlCommand(find, con);
comm.Parameters.Add("#name", SqlDbType.NChar).Value = txt;
con.Open();
comm.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = comm;
DataSet ds = new DataSet();
da.Fill(ds, "name");
GridView1.DataSource = ds;
GridView1.DataBind();
con.Close();
}
}
You can pass parameter to another page using QueryString. onclick event of button on First page do this:-
protected void Button1_Click(object sender, EventArgs e)
{
string search_word = TextBox1.Text.ToString();
Response.Redirect("~/secondpage.aspx?srch_word=" + search_word);
}
and on second page request the querystring:-
protected void Page_Load(object sender, EventArgs e)
{
string search = Request.QueryString["srch_word"];
//execute sql query to perform search operation
}
Your query looks off to me. Try "select * from product where name like '%#name%'"
Also for your parameters you can just cmd.Parameters.AddWithValue("name", nameVariable);
Not sure why you would need to specify the type in this situation.
your problem is not the SQL query, your problem is passing parameter to another page.
for this reason you can do it in at least 4 different ways.
Send Text by query string
Pass it via Post Data
Pass it via Cookie
Send it via Session
in this case you can use query string, but you have to care about security issue.
BTW, it depends on how you redirect to 2th page.

passing a datalist value using session in asp.net

I'm actually storing a value using session and then redirecting to other page using image button where based on the session value I'm fetching the Data from database. I'm getting an user defined exception in the line.
please help!
adap.Fill(dt1);//[SqlException (0x80131904): Incorrect syntax near '='.]
And this my coding.
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
ImageButton btn = sender as ImageButton;
string modelId = btn.CommandArgument;
Session["modelid"] = modelId;
Response.Redirect("details.aspx");
}
public partial class details : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=" + Session["modelid"], con);
DataTable dt1 = new DataTable();
adap.Fill(dt1);
DataList1.DataSource = dt1;
DataBind();
}
Cast the session object to a string first.
(String) Session["modelid"]
I recommend you to avoid using string concatenation for command creation - use parameters instead.
Also, you have to check whether Session["modelid"] has value or not, because parameter with null value will cause exactly the given message:
The parameterized query '(#id nvarchar(4000))select * from details1
where Modelid=#id' expects the parameter '#id', which was not supplied
So, the code will be:
protected void Page_Load(object sender, EventArgs e)
{
con.Open();
var id = Session["modelid"];
if (id != null)
{
SqlDataAdapter adap = new SqlDataAdapter("select * from details1 where Modelid=#id" , con);
adap.SelectCommand.Parameters.AddWithValue("#id", );
DataTable dt1 = new DataTable();
adap.Fill(dt1);
DataList1.DataSource = dt1;
DataBind();
}
}
Or use the Page.IsPostBack property if it is guaranteed that Session["modelid"] will be set after the first postback.
Or just use some default value for it.
P.S.: Also, it is not a good idea to use instance level connection where you can't Dispose (Close) it in a deterministic way. It is better to make it method level variable and use it with using clause:
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=VISH;Initial Catalog=VISH;Integrated Security=True"))
{
// ...
}
}

textBoxName.Text isn't getting the text entered by user, only the text that was set there on load

I have this textbox:
<asp:TextBox ID="txtDescription" runat="server" Height="90%" TextMode="MultiLine" Width="90%"></asp:TextBox>
and I set its' text value:
description = reader["Description"].ToString();
txtDescription.Text = description;
This is for editing the "description" so I have the existing description in the box and then want to get the text that is in the box at the end as it has been altered.
However I do:
string newDecription = txtDescription.Text;
and the value is that which it was initially set as. The above code to get the text value is ran on a submit button, so isn't somehow running and getting the value before it has been edited.
CONTEXT
protected void Page_Load(object sender, EventArgs e)
{
getValues();
}
string ID = 1;
protected void getValues()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand("SELECT Name,Stock,Price250g,Price1kg,Description,StockOrdered FROM Stock WHERE id = #ID", conn))
{
comm.Parameters.AddWithValue("#ID", ID);
conn.Open();
using (SqlDataReader reader = comm.ExecuteReader())
{
while (reader.Read())
{
price250g = reader["Price250g"].ToString();
price1kg = reader["Price1kg"].ToString();
name = reader["Name"].ToString();
description = reader["Description"].ToString();
stock = reader["Stock"].ToString();
stockOrdered = Convert.ToBoolean(reader["StockOrdered"].ToString());
lblName.Text = name;
lbl250g.Text += price250g.Remove(price250g.Length - 2);
lbl1kg.Text += price1kg.Remove(price1kg.Length - 2);
lblStock.Text = stock + "g";
cbStockOrdered.Checked = stockOrdered;
txtDescription.Text = description;
}
}
}
}
private void addAddressToOrder()
{
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand("UPDATE Stock SET Name=#name, Stock=#stock, Price250g=#price250, Price1kg=#price1kg, Description=#description, StockOrdered=#ordered WHERE Id=#ID", conn))
{
cmd.Parameters.AddWithValue("#ID", ID);
cmd.Parameters.AddWithValue("#description", txtDescription.Text);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#price250", txtPrice250g.Text);
cmd.Parameters.AddWithValue("#price1kg", txtPrice1kg.Text);
stock = ddAddStock.SelectedValue + stock;
cmd.Parameters.AddWithValue("#stock", stock);
cmd.Parameters.AddWithValue("#ordered", cbStockOrdered.Checked);
conn.Open();
cmd.ExecuteNonQuery();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
addAddressToOrder();
Response.Redirect("~/Admin/AdminHome.aspx");
}
This commonly happens when you do this:
protected void Page_Load(object sender, EventArgs e)
{
// other code
txtDescription.Text = description;
}
The reason is because of the page lifecycle events. Page_Load executes every time the page is loaded. This includes post-backs. (After all, you need to load the page in order to interact with it.) And it runs before any button handlers or other similar control events. So if this code, which writes a value to the text box, is executing before you read a value from the text box then it's going to overwrite that value.
Any code in Page_Load (or similar page initialization events) which shouldn't run on post-backs needs to be wrapped in a conditional:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// other code
txtDescription.Text = description;
}
}

Datagrid refresh not working

I have a datagrid to display some information from a SQL table, and then a simple textbox and button to allow users to add records to the database. Problem is, when the user clicks Add, the datagrid SHOULD update, but it doesn't, any ideas? The code in question is as follows:
protected void Page_Load(object sender, EventArgs e)
{
username.Text = Session["username"].ToString();
datetime.Text = DateTime.Now.ToString();
BindData();
}
protected void BindData()
{
string SQLQuery = "SELECT * From Filters";
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
DataSet resultsDataSet = new DataSet();
MyConn.Open();
OleDbDataAdapter DataAdapter = new OleDbDataAdapter(SQLQuery, MyConn);
DataAdapter.Fill(resultsDataSet);
DGFilters.DataSource = resultsDataSet;
DGFilters.DataBind();
if (resultsDataSet.Tables[0].Rows.Count == 0)
{
no_records.Visible = true;
DGFilters.Visible = false;
}
else
{
DGFilters.Visible = true;
no_records.Visible = false;
}
MyConn.Close();
}
protected void AddFilter_Click(object sender, EventArgs e)
{
OleDbConnection MyConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString);
MyConn.Open();
string SQLInsert = "INSERT INTO Filters (FilterString) VALUES ( '" + FilterToAdd.Text + "')";
OleDbCommand MyCmd = new OleDbCommand(SQLInsert, MyConn);
MyCmd.ExecuteNonQuery();
MyConn.Close();
DataBind();
}
Any ideas?
At the bottom of your AddFilter_Click method you need to call your own BindData() so the grid can be refreshed with the new record. Right now you're calling DataBind(), which is a method on the base class Control, which is being applied to your entire web form. I'm guessing this isn't doing much of anything.
Also, in your Page_Load method, you can probably change this:
BindData();
to
if (!Page.IsPostBack)
BindData();
so that you don't bind your grid twice when the user clicks on the 'add' button.

Categories

Resources