The Update Statement is not working - c#

protected void Button6_Click(object sender, EventArgs e)
{
Random rnd = new Random();
string resetpassword = rnd.Next(5000, 100000).ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString);
conn.Open();
string reset = "UPDATE Users SET" + " Password=#pass" + " WHERE UserName=#user";
SqlCommand com = new SqlCommand(reset, conn);
com.Parameters.AddWithValue("#pass", resetpassword);
com.Parameters.AddWithValue("#user", TextBox1.Text);
conn.Close();
}
For some reason, the password is not updated.

You forgot to execute the query:
int cnt = com.ExecuteNonQuery();
The method returns the number of affected rows.

Execute query
protected void Button6_Click(object sender, EventArgs e)
{
Random rnd = new Random();
string resetpassword = rnd.Next(5000, 100000).ToString();
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["HealthDBContext"].ConnectionString);
conn.Open();
string reset = "UPDATE Users SET" + " Password=#pass" + " WHERE UserName=#user";
SqlCommand com = new SqlCommand(reset, conn);
com.Parameters.AddWithValue("#pass", resetpassword);
com.Parameters.AddWithValue("#user", TextBox1.Text);
com.ExecuteNonQuery();
conn.Close();
}

Related

why i get this error when i do allow paging True The data source does not support server-side data paging

I had opened a related topic before, but I realized the problem now. When I set allow paging correctly in the properties of gridview in web form.aspx, I get this error. I don't know if the codes I wrote in aspx.cs browser cause this problem, please help
'''
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GVbind();
}
}
void clear()
{
txtName.Text = "";
txtPhone.Text = "";
txtAdd.Text = "";
}
protected void btnInsert_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[idus] VALUES ('" + txtName.Text + "', '" + txtPhone.Text + "', '" + txtAdd.Text + "')", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
Response.Write("<script>alert('Data inserted successfully') </script>");
con.Close();
}
GVbind();
clear();
}
//protected void btnDelete_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"DELETE FROM [dbo].[idus]
// WHERE [ID]='" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data deleted successfully");
// con.Close();
//}
//protected void btnUpdate_Click(object sender, EventArgs e)
//{
// SqlCommand cmd = new SqlCommand(#"UPDATE [dbo].[idus]
// SET[ID] = '" + txtID.Text + "',[name] = '" + txtName.Text + "',[phone] = '" + txtPhone.Text + "',[address] = '" + txtAdd.Text + "' WHERE [ID]= '" + txtID.Text + "'", con);
// con.Open();
// cmd.ExecuteNonQuery();
// Response.Write("Data updated successfully");
// con.Close();
//}
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GVbind();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int ID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
string name = ((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text;
string phone = ((TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0]).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text;
con.Open();
SqlCommand cmd = new SqlCommand("update [dbo].[idus] set name='" + name + "', phone='" + phone + "', address='" + address + "' where ID = '" + ID + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been updated') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GVbind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
con.Open();
int id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Value.ToString());
SqlCommand cmd = new SqlCommand("delete from [dbo].[idus] where ID='" + id + "'", con);
int t = cmd.ExecuteNonQuery();
if (t > 0)
{
con.Close();
Response.Write("<script>alert('Data has been deleted') </script>");
GridView1.EditIndex = -1;
GVbind();
}
}
protected void DisplayData()
{
SqlConnection con = new SqlConnection("Data Source=MERIH-PC;Initial Catalog=aspidus;Integrated Security=True");
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter("select * from [dbo].[idus]", con);
con.Open();
da.Fill(dt);
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging1(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GVbind();
'''
enter image description here
enter image description here
You are assigning the GV a "reader", and you can't use a reader - you have to fill a table, or use some other ennumberable collection. Say like a data table.
So, this code:
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows == true)
{
GridView1.DataSource = dr;
GridView1.DataBind();
}
}
Change to :
protected void GVbind()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from [dbo].[idus]", con);
Datatable dt = new dt();
dt.load(cmd.ExecuteReader());
GridView1.DataSource = dt;
GridView1.DataBind();
}
So, while you can "shove" the GV to a reader directly? If you going to use paging, then you can't shove into the GV a reader - since paging does not work with a non innumerable type of data set (like a reader).
So, just load up a data table. And note how I did not even need a data adaptor to load up a data table (the data table has a .Load command for you. (so, you can shorten your other code this way also).

How to save the name of dropdownlist instead of its ID?

I m been working on a project in which i m facing an issue
I m having two drop down list which are Select category (ddlcategory) and select subcategory (ddlsubcategory) here are they
When I'm saving the data i m getting the ID saved into my database instead of category name and subcategory name Here is my database values :
Here is my back code i have implemented :
String constr = #"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\PROJECT SEM6\Online Tours and Travels\App_Data\ToursandTravels.mdf;Integrated Security=True;User Instance=True";
string query = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindCategoryDropdown();
}
}
protected void btnpreviewwebsite_Click1(object sender, EventArgs e)
{
Response.Redirect("http://localhost:50550/Online Tours and Travels/index.aspx");
}
protected void btnlogout_Click(object sender, EventArgs e)
{
Session.Abandon();
Session.Clear();
Response.Redirect("http://localhost:50550/Online Tours and Travels/Admin Panel/LoginForm.aspx");
}
protected void BindCategoryDropdown()
{
//conenction path for database
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from category", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlcategory.DataSource = ds;
ddlcategory.DataTextField = "Cat_name";
ddlcategory.DataValueField = "Cat_id";
ddlcategory.DataBind();
ddlcategory.Items.Insert(0, new ListItem("--Select--", "0"));
ddlsubcategory.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void ddlcategory_SelectedIndexChanged(object sender, EventArgs e)
{
int categoryid = Convert.ToInt32(ddlcategory.SelectedValue);
SqlConnection con = new SqlConnection(constr);
con.Open();
SqlCommand cmd = new SqlCommand("select * from subcategory where catid=" + categoryid, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
ddlsubcategory.DataSource = ds;
ddlsubcategory.DataTextField = "subcatname";
ddlsubcategory.DataValueField = "subcatid";
ddlsubcategory.DataBind();
ddlsubcategory.Items.Insert(0, new ListItem("--Select--", "0"));
}
protected void btnsave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(constr);
String pathName1 = "~/packageimages/" + Path.GetFileName(fileuploadpic1.PostedFile.FileName);
String pathName2 = "~/packageimages/" + Path.GetFileName(fileuploadpic2.PostedFile.FileName);
String pathName3 = "~/packageimages/" + Path.GetFileName(fileuploadpic3.PostedFile.FileName);
query =
"insert into package(packname,catid,categoryname,subcatname,packageprice,pic1,pic2,pic3,detail) values('"+txtpackagename.Text+"','"+txtcategoryid.Text+"','"+ddlcategory.Text+"','"+ddlsubcategory.Text+"','"+txtpackageprice.Text+"','"+pathName1+"','"+pathName2+"','"+pathName3+"','"+txtdetails.Text+"') ";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
fileuploadpic1.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic1.FileName));
fileuploadpic2.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic2.FileName));
fileuploadpic2.SaveAs(Server.MapPath("~/packageimages/" + fileuploadpic3.FileName));
txtpackagename.Text = "";
txtcategoryid.Text = "";
txtpackageprice.Text = "";
txtdetails.Text = "";
string message = "Package Added !!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
Please do help ! Thank You
answering your question - you need to use
ddlcategory.SelectedItem.Text not ddlcategory.Text
But as suggested, first do learn about query parameters
for example here
And about using statement for example here
The name of a Control gets generated by aspnet itself. Depending where in the control tree a Control is located, it could become something like this:
ctl00$ContentPlaceHolder1$ctl00$TextBox1
But if you really want to get the name, you can use UniqueID.
string controlName = TextBox1.UniqueID;

When entering data does not update the text box

Hello friends I am writing to pull information from the base TextBox and I want to update the database through the TextBox , but when I enter the new value is the old value does not always save the new value
Code behind
protected void Page_Load(object sender, EventArgs e)
{
string ID = Request.QueryString["Id"].ToString();
SqlConnection baglan = new SqlConnection(ConnectionString3);
baglan.Open();
SqlCommand com = new SqlCommand("Select * from pkategori where Id='" + ID + "'", baglan);
SqlDataReader oku = com.ExecuteReader();
if (oku.Read())
{
baslik.Text = oku["Tanim"].ToString();
detaylar.Text = oku["Detaylar"].ToString();
}
else
{
baslik.Text = "Bulunmadı";
}
}
Button Click Event
string ust = Request.QueryString["ID"].ToString();
SqlConnection baglanti = new SqlConnection(ConnectionString3);
baglanti.Open();
string kayit = "update pkategori set Tanim=#Tanim where Id=#Id";
SqlCommand komut = new SqlCommand(kayit, baglanti);
komut.Parameters.AddWithValue("#Tanim", baslik.Text);
komut.Parameters.AddWithValue("#Id", ust);
komut.ExecuteNonQuery();
baglanti.Close();
Simple, just wrap your code in Page_Load in a !IsPostBack-check:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string ID = Request.QueryString["Id"].ToString();
SqlConnection baglan = new SqlConnection(ConnectionString3);
baglan.Open();
SqlCommand com = new SqlCommand("Select * from pkategori where Id='" + ID + "'", baglan);
SqlDataReader oku = com.ExecuteReader();
if (oku.Read())
{
baslik.Text = oku["Tanim"].ToString();
detaylar.Text = oku["Detaylar"].ToString();
}
else
{
baslik.Text = "Bulunmadı";
}
}
}
Otherwise you are loading the text from the database and the changed value is overwritten.

EndExecuteNonQuery Error

i have an error as which is on the button click event, as its shows me an error message on this line:
com.EndExecuteNonQuery();
message text: Error 2 No overload for method 'EndExecuteNonQuery' takes 0 arguments
Thank you for your support
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string cmdStr = "Select count(*) from UserInfo where UID = '" + UsrNme.Text + "'";
SqlCommand com = new SqlCommand(cmdStr, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
chkusrnamlbl.Visible = true;
}
conn.Close();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["usradmadslistview"].ConnectionString);
conn.Open();
string insertquery = "insert into UserInfo (UID,FN,LN,Password,Email,CountID,State,City) Values (#username,#firstn,#lastn,#passbox,#email1,#country,#state,#city)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.AddWithValue("#username", UsrNme.Text);
com.Parameters.AddWithValue("#firstn", fnbox.Text);
com.Parameters.AddWithValue("#lastn", lnamebox.Text);
com.Parameters.AddWithValue("#passbox", passtxtbx1.Text);
com.Parameters.AddWithValue("#email1", emailbox.Text);
com.Parameters.AddWithValue("#country", DrDncoundrlst.SelectedItem.ToString());
com.Parameters.AddWithValue("#state", DropDownListSwestate.SelectedItem.ToString());
com.Parameters.AddWithValue("#city", citytxtbox.Text);
com.EndExecuteNonQuery();
Response.Redirect("User panel.aspx");
conn.Close();
}
catch(Exception ex) {
Response.Write("Error:" + ex.ToString());
}
EndExecuteNonQuery requires an IAsyncResult parameter as mentioned here in MSDN.
Also, is this just a code snippet? Because I think you would want to use com.ExecuteNonQuery() instead. EndExecuteNonQuery is the end pair for asynchronously executing SQL statements.

Object reference not set to an instance of an object for asp.net

protected void Page_Load(object sender, EventArgs e)
{
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
string sql = "Select password from Profile where userid = '" + Session["userid"] + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr; // to hold reference of datareader returned
//prepare a place - datatable to hold the data
DataTable dt = new DataTable();
//setting up command
cmd.CommandText = sql;
cmd.Connection = con;
//connection and execute command
con.Open();
dr = cmd.ExecuteReader();
dt.Load(dr); // copy data from datareader to datatable
string pwdcheck;
pwdcheck = dt.Rows[0]["password"].ToString();
if (tb_verify.Text.Equals(pwdcheck))
{
string password = tb_pwd.Text;
sql = "Update Profile set password ='" + password + "'";
sql = sql + "where userid = '" + Session["userid"] + "'";
cmd.CommandText = sql;
cmd.Connection = con;
try
{
cmd.ExecuteNonQuery();
lb_msg.Text = "Password changed succesfully";
}
catch (Exception ex)
{
lb_msg.Text = "Problems encountered " + ex.Message;
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
else
lb_msg.Text = "Old password Incorrect";
}
protected void lblClick(object sender, EventArgs e)
{
FormsAuthentication.SignOut();
Session.Clear(); // This may not be needed -- but can't hurt
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
}
}
lb_msg2.Text = "Hello " + Session["userid"].ToString() + "!";
there is an error at the line above with
Object reference not set to an instance of an object the change password feature was working before.
In your case Session["userid"] must be NULL,handle it

Categories