ASP.NET: Records in database don't get updated - c#

I'm trying to update my database records, but no changes are made and no error messages. I checked the syntax, the values I'm sending, everything is just fine ..
any suggestions?
This is my code which executed when [save] button is clicked:
ds.UpdateCommand = "UPDATE Users
SET Fullname='" + fname.Text + "',
Permission='" + per.SelectedValue + "',
Email='" + email.Text + "',
phone='" + phone.Text + "'
WHERE UserID=" + Session["userID"].ToString();
ds.Update();
I'm reading values from form filled by the user
ds is an SqlDataSource
If I have to add more details let me know
EDITS:
This page is for user to update his/her information
I'm setting the form values on Page_Load depending on the users information already exist in database.
the user edits his/her info and click [Save]
after setting braekpoints, I found that query string is taking the default values not the new ones. what should I do?
The entire code:
protected void Page_Load(object sender, EventArgs e)
{
Session["userID"] = Request.QueryString["id"];
SqlConnection cn = new SqlConnection();
cn.ConnectionString = ds.ConnectionString;
cn.Open();
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandText = "select * from Users where UserID='" + Session["userID"].ToString() + "'";
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
uname.Text = dr["username"].ToString();
fname.Text = dr["Fullname"].ToString();
per.SelectedValue = dr["Permission"].ToString();
email.Text = dr["Email"].ToString();
phone.Text = dr["phone"].ToString();
}
else Response.Redirect("Default.aspx");
dr.Close();
cn.Close();
}
protected void Button3_Click(object sender, EventArgs e)
{
ds.UpdateCommand = "update Users set Fullname='" + fname.Text + "', Permission='" + per.SelectedValue + "', Email='" + email.Text + "', phone='" + phone.Text + "' where UserID=" + Session["userID"].ToString();
ds.Update();
Response.Redirect("control_pan.aspx");
}

Basically, if you have a DataSet and you want to use that to update your database, you need to:
define the UpdateCommand as shown in the MSDN documentation to reference the columns from the DataTable which will be used to update
update an existing row in one of your DataTables inside the DataSet
once you've done that, then you can call .Update() on the data set (or data table) to execute the update - ADO.NET will check for updates to any of the rows of the DataTable, and if an update is found, then the UpdateCommand will be executed, with the parameters bound to the values of the DataTable's row in question
I would also recommend to read up on how the ADO.NET data model and using DataSets and DataTables works in detail - e.g. here Update Data Using .NET DataSets
The alternative, of course, would be to create a SqlConnection and a SqlCommand, using a parametrized query to do the insert yourself, without all the hassle and effort involved with DataSets and DataTables. But in that case, make sure to ALWAYS use parameterized queries (and NEVER just concatenate together your SQL statement including values straight from user input .....) - see why here

I suspect the Session["UserID"] is null. To check this set break point on ds.Update(); by putting the cursor on it then pressing F9.
To see the result query hover your mouse pointer over ds.UpdateCommand when break point pauses operation.
Update: put the code in the page load to be executed only once that is when first the page loads
if(!IsPostBack)
{
//put your code here
}
Update
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Session["userID"] = Request.QueryString["id"];
SqlConnection cn = new SqlConnection();
cn.ConnectionString = ds.ConnectionString;
cn.Open();
SqlCommand cm = new SqlCommand();
cm.Connection = cn;
cm.CommandText = "select * from Users where UserID='" + Session["userID"].ToString() + "'";
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
uname.Text = dr["username"].ToString();
fname.Text = dr["Fullname"].ToString();
per.SelectedValue = dr["Permission"].ToString();
email.Text = dr["Email"].ToString();
phone.Text = dr["phone"].ToString();
}
else Response.Redirect("Default.aspx");
dr.Close();
cn.Close();
}
}

I seriously doubt you've provided enough details here to resolve the issue.
That type is UserID? Does the value need to be enclosed in quotes?
Are you setting the right value in your WHERE clause, and does that value existing in the database? You need to look at the resulting query string and then run it manually to determine what might be wrong.
Also, shouldn't you have the # character prefix for your string so that newlines are part of your string? Is this really what your code looks like?
Of course, without knowing more about the code, it's hard to say what else it might be as well.

Related

How to pass data between ASP.net, sql server and c#

I'm trying to develop a web site that receives data from SQL server, then show info on listbox and textbox, and when user select an option then insert data to a table in the database.
My ASP.NET controls are:
<asp:ListBox ID="ListBox1" ClientIDMode="static" runat="server"></asp:ListBox>
<asp:Button ID="btnInsert" runat="server" Text="Start" OnClick="btnInsert_Click" />
I need the data loaded to a listbox, but not sure how to do directly. To retrieve the info and see if its working I did this:
protected void Page_Load(object sender, EventArgs e){
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
GridView2.DataSource= reader;
GridView2.DataBind();
con.Close();
var nProject = GridView2.Rows.Count;
for (int b = 0; b < nProject ; b++)
{
ListBox1.Items.Add(GridView2.Rows[b].Cells[0].Text);
}
}
Then I tried to set the selected info to a textbox, but nothing happens (because I managed to insert data from textbox to a SQL Server INSERT) :
protected void ListBox1_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox2.Text = ListBox1.SelectedValue;
Response.Write("ListBox selectedIndexChanged");
}
The info is send back to the database with a button click:
protected void btnInsert_Click(object sender, EventArgs e)
{
var IP = "111.111.11";
txtStatus.Text = "Start";
txtProject.Text = "PR-02";
var indice = 0;
// This always returns "0"
if (ListBox1.SelectedItem != null)
{
indice = ListBox1.SelectedIndex;
}
txtProject.Text = indice.ToString();
// Sql INSERT works fine, but only with info manually created. I can't get the real info to work
SqlConnection con = new SqlConnection("****");
SqlCommand cmd = new SqlCommand(#"INSERT INTO [dbo].[table3]
([project]
,[user_task]
,[status]
,[ip]
,[location])
VALUES
('" + txtProject.Text + "', '" + txtUser.Text + "', '" + txtStatus.Text + "', '" + txtIP.Text + "', '" + txtLocation.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
The Page_Load is one of the first events to run every time there is a call to the server, this means that it runs before the btnInsert_Click event.
This means that you are repopulating the ListBox1 before checking the SelectedItem, this is why it always returns "0"
You have to consider this and use something like
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack || Page.IsCallback) return;
(...)
}
It is hard to understand what you want to do, but I think the ListBox1_OnSelectedIndexChanged is useless if you correct the Page_Load event.
Side notes:
You should really start by putting using statements where you can (on SqlConnection and SqlCommand)
Watch out for Sql Injections, may be a simple test program, but you should NEVER, EVER do this: #"INSERT INTO (...) VALUES ('" + txtProject.Text + "'"
use parameters instead:
using(SqlConnection con = new SqlConnection("****"))
using(SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[table3] ([project]) values (#project)", con))
{
cmd.Parameters.AddWithValue("#project", txtProject.Text);
}
It seems you are using .Net Framework with aspx pages, you should really consider using newer technologies (.net core).

how to notify when stock levels have reached below a certain level c# ASP.NET

I'm stuck with a part of a project.
I have a database set up in SQL server with a table called stockTable which keep account of the four different types of materials needed.
I am using c# and ASP.net and doing this is Visual studio 2013.
I ultimately want to be able to be notified when these stock levels have reached below a certain level (EG: 200) and then email the manager to order some more materials.
I have the materials within a table and they are out putted by using a placeholder.
I am unsure in how to check the values in this placeholder and compare it to a standard level (EG:200).
This is how the table is created and shown on the webform.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * from [StockTable]";
cmd.Connection = con;
SqlDataReader rd = cmd.ExecuteReader();
table.Append("<table border='1'>");
table.Append("<tr><th>ID</th><th>Amount Of Stickers</th><th>Amount of Small Jars</th><th>Amount of Large Jars</th><th> Amount of Lids</th>");
table.Append("</tr>");
if (rd.HasRows)
{
while (rd.Read())
{
table.Append("<tr>");
table.Append("<td>" + rd[0] + "</td>");
table.Append("<td>" + rd[1] + "</td>");
table.Append("<td>" + rd[2] + "</td>");
table.Append("<td>" + rd[3] + "</td>");
table.Append("<td>" + rd[4] + "</td>");
table.Append("</tr>");
}
}
table.Append("</table");
PlaceHolder1.Controls.Add(new Literal { Text = table.ToString() });
rd.Close();
}
}
Does anyone know how to do this, was thinking an if statement comparing the values but i am unsure of how to go about this.
if a anyone has suggestions or snippets of code, it would be greatly appreciated, or easier ways in order to email the manager when stock levels are low.

Show data in Textboxes from database in C#

Is there anything wrong with my code? It is not showing data in textboxes. The same funtion is working for another table in database but not for this one.
private void metroButton1_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
cmd = new SqlCommand(query, con);
con.Open();
try
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
// metroTextBox1.Text = (read["ID"].ToString());
metroTextBox2.Text = (read["Name"].ToString());
metroTextBox3.Text = (read["F_Name"].ToString());
metroTextBox4.Text = (read["Std_Age"].ToString());
metroTextBox5.Text = (read["Address"].ToString());
metroTextBox6.Text = (read["Program"].ToString());
metroComboBox1.Text = (read["Course"].ToString());
}
}
}
finally
{
con.Close();
}
}
you need to give column names in the select statement or select *
for example :
String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
Not related to Question: you can change the while loop to if condition if you have one record for given id. even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record.
Update :
There isn't anything wrong with Syntax because the same syntax is
working for modifying teacher funtion.
No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error

C# edit button to Access database

I have a particular part of an inventory interface that requires an employee to select his or her name from a combo box and then scan a product to the table assigned to the name of the employee.
My curiosity is: When hitting the EDIT, ADD OR DELETE button it knows what table to perform this function in from a Switch - Case statement with that employee name on it. The problem is, the piece of code is long for each employee, especially for 9 employees that each have a Switch - Case statement.
Any advice on how to simplify this or shorten the code? I do understand in advance about the parameterized SQL that I am failing to use. Just trying to accomplish this first.
private void btnAdd_Click(object sender, EventArgs e)
{
ActiveControl = txtSerialN;
if (!string.IsNullOrEmpty(txtSerialN.Text) && !string.IsNullOrEmpty(cboEmpName.Text))
switch (cboEmpName.SelectedItem.ToString().Trim())
{
case "John Doe":
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO JohnDoe(SerialNumber,PartNumber,DateEntered,Customer) values ('" + txtSerialN.Text + "','" + txtPart.Text + "','" + txtDate.Text + "','" + txtCustomer.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Inventory Added".PadLeft(23));
connection.Close();
txtSerialN.Clear();
txtPart.Clear();
txtDate.Clear();
txtCustomer.Clear();
command.CommandText = "SELECT * FROM JohnDoe ORDER BY PartNumber";
OleDbDataAdapter db = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
db.Fill(dt);
dataGridEmpParts.DataSource = dt;
}
catch (OleDbException)
{
string strmsg = "THIS SERIAL NUMBER ALREADY EXISTS ! , Please try again";
MessageBox.Show(strmsg, "YOU CAN'T ENTER THE SAME ONE AGAIN", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1);
connection.Close();
}
break;
}
}
I would rather put up a lookup table that will have columns such as EmployeeName, AssignedTable and dynamically construct the commandtext based on the parameter values.
I suspect this problem could more efficiently be fixed by altering the database. Perhaps even as simple as adding a field for employee name.

Using checkbox text values to perform search in database

I am working on a project where the user is displayed a image with hotspots. Upon clicking one part he is displayed a dynamically generated checkbox for which the values are picked from database (hotspot are mapped to value displayed).
The problem I am facing is that when the value is a single word (ex. swelling) the code works fine and fetches the possible diseases, but when there are words like (ex. joint pain or nausea with vomiting) i.e the ones which contain space between them (more than one word as a checkbox value) the code does not work.
Here is the code
protected void Button2_Click(object sender, EventArgs e)
{
if (TextBox2.Text != "")
{
connection.Open();
symptons = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Text).ToArray());
Label1.Text = symptons;
string query = symptons.Replace(", ", "','");
string cm = "select distinct dname from disease d inner join diseasesymptom ds on ds.did=d.did inner join symptom s on s.sid=ds.sid where s.sname in ('" + query + "')" + "and days >" + TextBox2.Text + " and days<41 order by (days) desc;";
if (symptons != "")
{
MySqlCommand cmd = new MySqlCommand(cm, connection);
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
cmd.Connection = connection;
sda.SelectCommand = cmd;
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
else
{
Label1.Text = "select at least one symptom";
}
}
else
{
string script = "alert(\"We can't predict without all inputs :(\");";
ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
}
}
I think it has something to do with Join and Replace that I am performing.
never mind guys..I got it. I was missing a column value in database that helped in searching (hint : its 'days') . Anyway thanks for anyone who read this. :)

Categories

Resources