I have problem with updating data.
Sample:
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
string id = row.Cells[1].Text;
Response.Redirect("edit.aspx?id="+id);
}
after this code transition to another page with update cmd.
protected void Page_Load(object sender, EventArgs e)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
con.Open();
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.ExecuteNonQuery();
Response.Redirect("main.aspx");
}
I clicked button, and was redirected to main page. But nothing else, update doesn't work. :(
where do I have a problem?
I don't really know where is the problem, but for sure you need to refactor your update statement using the IDisposable capabilities of the connection object, it shoul look like this:
using (SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString))
{
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, connection);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
Your update sql query looks fine:
con.Open();
com.ExecuteNonQuery();
con.Close();
that is try using this function instead and debug it to see if there is a sql exception thrown.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ARM_TSPConnectionString"].ConnectionString);
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, Class=#Class WHERE ID=#ID";
SqlCommand cmd = new SqlCommand(upd, con);
cmd.Parameters.AddWithValue("#ID", IDLBL.Text);
cmd.Parameters.AddWithValue("#SecondName", SName.Text);
cmd.Parameters.AddWithValue("#Graduate", Ocenka.SelectedValue);
cmd.Parameters.AddWithValue("#Class", Klass.SelectedValue);
cmd.Parameters.AddWithValue("#Name", Name.Text);
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("main.aspx");
}
catch (SqlException e)
{
}
}
UPDATE: Think I've realised why it's not working for you... you have a column called class... but class in sql server is a reserved keyword... so you must put square brackets around it ... like so
Edited the escaping (made a mistake as pointed out by Hans in the comment below)
string upd = "UPDATE Info SET Name=#Name, SecondName=#SecondName, Graduate=#Graduate, [Class]=#Class WHERE ID=#ID";
The problem was found.Just add in Page_Load if(!isPostBack)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
foreach (DataRowView drv in dv)
{
IDLBL.Text = drv["ID"].ToString();
Name.Text = drv["Name"].ToString();
SName.Text = drv["SecondName"].ToString();
Ocenka.Text = drv["Graduate"].ToString();
Klass.Text = drv["Class"].ToString();
}
}
Now, all working good.
Related
private void Delete_Click(object sender, EventArgs e)
{
//i have used this query for delete button
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter();
OleDbConnection con = new
OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb");
con.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Users\HP\Desktop\sd.mdb";
con.Open();
//this is the query i have used
OleDbCommand cmd = new OleDbCommand("DELETE FROM car_model WHERE Description ='" + des+ "'", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Data Deleted");
con.Close();
}
//i have table named:car_model & attribute as Description
Your quotes don't look right, but my eyes are not great and anyway, the compiler would pick that up immediately, so I guess it's something else.
private void BtnDelete_Click(object sender, RoutedEventArgs e)
{
DataRowView drv = (DataRowView)dataGridView1.SelectedItem;
int id = drv.Row[0];
if(drv != null)
{
delete(id);
}
}
public void delete(int id)
{
try
{
con.Open();
OleDbCommand comm = new OleDbCommand("Delete From Car_Model Where Description = #Des", con);
comm.Parameters.AddWithValue("#Des", id);
comm.ExecuteNonQuery();
}
catch(OleDbException ex)
{
MessageBox.Show("DataConnection not found!", ex);
}
finally
{
con.Close();
}
Also, use the '#' character to prevent SQL Injection issues. I don't think this is necessarily a problem with MS Access, but it's a good habit to get into.
https://www.w3schools.com/sql/sql_injection.asp
I have piece of query that search database from text box.
My question is how can insert search result column by column to separated text box, I mean each column go to one textbox.
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
com.ExecuteNonQuery();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Try this :
private void searchbtn_Click(object sender, EventArgs e)
{
SqlConnection sql = new SqlConnection("Your String Connection");
SqlDataAdapter adapter = new SqlDataAdapter(#"Select Name, FileName From Table Where Name Like #Name", sql);
adapter.SelectCommand.Parameters.AddWithValue("#Name", string.Format("%{0}%", textBox1.Text));
}
I assume that, your search will return only one row.
You can use datareader to achieve that. I modified your function with below code:
private void searchbtn_Click(object sender, EventArgs e)
{
SqlCeConnection con = new SqlCeConnection(#"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");
try
{
con.Open();
string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;
SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);
SqlCeDataReader sqlReader = com.ExecuteReader();
while (sqlReader.Read())
{
txtID.text = sqlReader.GetValue(0).ToString();
txtRadif.text = sqlReader.GetValue(1).ToString();
txtName.text = sqlReader.GetValue(2).ToString();
}
sqlReader.Close();
com.Dispose();
con.Close();
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
}
Note: Your code is vulnerable to sqlinjection. Learn things to avoid it.
I would like ask if you could help me with my codes as I don't get the result that I want which is to load the details of a particular paper from drop down list.
Currently, when the page loads, the details of the selected item will load up. But when I try to choose another item from the drop down list, corresponding details won't show up, the previous one still remains instead.
Under the properties of drop down list, I also set autopostback to yes so that it will automatically load the corresponding details of the item selected.
Please see codes below
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetPaper();
GetInk();
GetPaperDetails(ddlPaperName.SelectedItem.Value);
//pnlPrinting.Visible = true;
}
}
protected void btnCompute_Click(object sender, EventArgs e)
{
}
protected void btnCancel_Click(object sender, EventArgs e)
{
}
private void GetPaper()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "PaperID";
ddlPaperName.DataTextField = "PaperName";
ddlPaperName.DataBind();
data.Close();
con.Close();
}
private void GetPaperDetails(string paper)
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Papers WHERE PaperID=" + paper;
SqlDataReader data = com.ExecuteReader();
while (data.Read())
{
lblPaperPrice.Text = data["PaperPrice"].ToString();
lblDescription.Text = data["PaperDescription"].ToString();
lblSpecification.Text = data["PaperSpecification"].ToString();
imgPaper.ImageUrl = "../" + data["PaperImage"].ToString();
}
data.Close();
con.Close();
}
private void GetInk()
{
con.Open();
SqlCommand com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.Text;
com.CommandText =
"SELECT * FROM Inks";
SqlDataReader data = com.ExecuteReader();
ddlPaperName.DataSource = data;
ddlPaperName.DataValueField = "InkID";
ddlPaperName.DataTextField = "InkName";
ddlPaperName.DataBind();
while (data.Read())
{
lblInkPrice.Text = data["InkPrice"].ToString();
}
data.Close();
con.Close();
}
protected void ddlPaperName_SelectedIndexChanged(object sender, EventArgs e)
{
GetPaperDetails(ddlPaperName.SelectedItem.Value);
}
Looking forward to your feedback here. Thanks!
Set AutoPostBack property to true of your drop down list.
us this code, for that,
if (!IsPostBack == true)
{
drpdownaccountnamebind();
drpdowncountrynamebind();
}
i hope this will be helpful,
rIdThere are two text boxes in page. One is for UserId and the other one is for email. Both are retrieved data from table aspnet_membership and are set 'read-only'.
For email text box, it will change read-only = false. Then user get to enter a new email then hit button save. It should update the email in table with the new email but unfortunately no changes made. Can some one tell me what should I remove/add to make it works. Here is my code.
protected void Page_Load(object sender, EventArgs e)
{
string email = Membership.GetUser(User.Identity.Name).Email;
MembershipUser currentUser = Membership.GetUser();
string UserId = currentUser.ProviderUserKey.ToString();
TextBox2.Text = email;
TextBox3.Text = UserId;
}
protected void Button4_Click(object sender, EventArgs e)
{
TextBox2.ReadOnly = false;
}
protected void Button3_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
}
I have refatored your code, now it should work
protected void Button3_Click(object sender, EventArgs e){
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_membership SET Email = #email WHERE UserName = #id1", conn);
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#email", TextBox2.Text);
cmd.Parameters.AddWithValue("#id1", TextBox3.Text);
try {
conn.Open();
cmd.ExecuteNonQuery();
}
catch(Exception ex){
throw ex;
}
finally{
conn.Close();
}
}
Look like you forgot to open connection
con.Open();
run command
cmd.ExecuteNonQuery();
and then close connection
con.Close();
You code is showing no signs of committing any data back to its Data Source.
You need a Data Adapter, and you need to set its Insert Command to the command above.
SQLDataAdapter adapt = new SQLataAdapter();
you then need to open a connection :-
conn.open();
adapt.UpdateCommand = cmd;
adapt.UpdateCommand.ExecuteNonQuery()
conn.close();
Hope This Helps.
You can try directly updating the user via Membership class in your button click event:
protected void Button3_Click(object sender, EventArgs e)
{
var memUser = Membership.GetUser(TextBox3.Text) //Fetch the user by user Id
memUser.Email = TextBox2.Text // Assign the new email address
Membership.UpdateUser(memUser) // update the user record.
}
I have a form wherein I populate content using stored procedure and I perform update actions on the content. Now my update button works fine. My problem is that each time I click on 'refresh' button in IE, the content gets updated and I don't want that to happen. I am new to .Net and all this ViewState stuff. Any help is appreciated..
Here is my code:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void BindGridView()
{
string constring = ConfigurationManager
.ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("spd_pc", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
cmd.Parameters.Add("#city", SqlDbType.VarChar).Value = txt_city.Text;
con.Open();
IDataReader idr = cmd.ExecuteReader();
GridView1.DataSource = idr;
GridView1.DataBind();
idr.Close();
con.Close();
}
}
}
protected void Button1_click(object sender, EventArgs e)
{
BindGridView();
}
private void DeleteRecords(int id)
{
string constring = ConfigurationManager.
ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("del_pc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
protected void ButtonDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
CheckBox chkb = (CheckBox)row.FindControl("CheckBox1");
if (chkb.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
if (!(id.Equals(System.DBNull.Value)))
{
DeleteRecords(id);
}
}
}
BindGridView();
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!IsCallback)
{
string active = "active";
string inactive = "inactive";
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkb = (CheckBox)row.FindControl("CheckBox1");
if (chkb.Checked)
{
int id = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Values[0]);
string status = row.Cells[5].Text;
if (!(id.Equals(System.DBNull.Value)))
{
if ((String.Equals(active, status)))
UpdateRecords(id);
if ((String.Equals(inactive, status)))
UpdateRecords(id);
}
}
}
}
}
private void UpdateRecords(int id)
{
string constring = ConfigurationManager.
ConnectionStrings["shaConnectionString"].ConnectionString;
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("upd_pc", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
conn.Open();
cmd.Parameters.Add("#id", SqlDbType.VarChar).Value = id;
cmd.ExecuteNonQuery();
conn.Close();
}
}
BindGridView();
}
}
yes, this will happen. the problem is you are refreshing the post event of the button click. the solution is to redirect back to page after the update is complete.
button_click(...)
{
//save to db
Response.Redirect(Request.Referrer);
}
or something like that.
Now if the user clicks refresh it will submit the GET request to load the page, rather the POST to issue the button click event.
If you search for Post Get Redirect (or something like that) you will find lots of articles on the topic. describing both the situation you encountered and why this solution works.