ASP.NET C# update query not working - c#

I am working on one project for the university and I want to say that I am pretty new in asp.net.
Please find below the code that I am experiencing problems with. The problem is that the update function is not working. In the page load I have some select queries and I load a data from the database into some textareas and textfields. This is working fine - it loads the sample data that I have added manually in my database.
I have buttons that should update the database on click.
This is the code for the buttons:
<a id="A1" class="button" onserverclick="box1_Click" runat="server">
<span>Запази полето <img src="notification-tick.gif" width="12" height="12" /></span>
</a>
This is the code behind:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class admin_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Loading the data from the database
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql1_title = "SELECT title FROM home WHERE id=1";
string sql1_image = "SELECT image FROM home WHERE id=1";
string sql1_text = "SELECT text FROM home WHERE id=1";
string sql2_title = "SELECT title FROM home WHERE id=2";
string sql2_image = "SELECT image FROM home WHERE id=2";
string sql2_text = "SELECT text FROM home WHERE id=2";
string sql3_title = "SELECT title FROM home WHERE id=3";
string sql3_image = "SELECT image FROM home WHERE id=3";
string sql3_text = "SELECT text FROM home WHERE id=3";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
//box1 data load
SqlCommand cmd1_title = new SqlCommand(sql1_title, conn);
conn.Open();
box1_title.Text = (string)cmd1_title.ExecuteScalar();
conn.Close();
SqlCommand cmd1_image = new SqlCommand(sql1_image, conn);
conn.Open();
box1_img.Text = (string)cmd1_image.ExecuteScalar();
conn.Close();
SqlCommand cmd1_text = new SqlCommand(sql1_text, conn);
conn.Open();
box1_text.InnerText = (string)cmd1_text.ExecuteScalar();
conn.Close();
//box2 data load
SqlCommand cmd2_title = new SqlCommand(sql2_title, conn);
conn.Open();
box2_title.Text = (string)cmd2_title.ExecuteScalar();
conn.Close();
SqlCommand cmd2_image = new SqlCommand(sql2_image, conn);
conn.Open();
box2_img.Text = (string)cmd2_image.ExecuteScalar();
conn.Close();
SqlCommand cmd2_text = new SqlCommand(sql2_text, conn);
conn.Open();
box2_text.InnerText = (string)cmd2_text.ExecuteScalar();
conn.Close();
//box3 data load
SqlCommand cmd3_title = new SqlCommand(sql3_title, conn);
conn.Open();
box3_title.Text = (string)cmd3_title.ExecuteScalar();
conn.Close();
SqlCommand cmd3_image = new SqlCommand(sql3_image, conn);
conn.Open();
box3_img.Text = (string)cmd3_image.ExecuteScalar();
conn.Close();
SqlCommand cmd3_text = new SqlCommand(sql3_text, conn);
conn.Open();
box3_text.InnerText = (string)cmd3_text.ExecuteScalar();
conn.Close();
}
}
protected void box1_Click(object sender, EventArgs e)
{
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql1 = "UPDATE home SET title=#title, image=#image, text=#text WHERE Id=1";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd2 = new SqlCommand(sql1, conn);
cmd2.Parameters.AddWithValue("#title", box1_title.Text);
cmd2.Parameters.AddWithValue("#image", box1_img.Text);
cmd2.Parameters.AddWithValue("#text", box1_text.InnerText);
conn.Open();
cmd2.ExecuteNonQuery();
conn.Close();
}
}
protected void box2_Click(object sender, EventArgs e)
{
}
protected void box3_Click(object sender, EventArgs e)
{
}
}
When I make a change to the title of the box1 and then click the button to update the database it is actually refreshing the page and loading the sample data again and my change is not saved.
Could you please help me with this?. There is no errors nothing.
Thank you guys very much.
PS: I have noticed that when I load the page in my browser and then delete the whole code block for the data load, make a change in the browser in one of the fields and then press the button it s actually updating the database. It is very strange...

This is because you need to take care about the ASP.NET lifecycle.
You need to check if its a PostBack (A postback occurs when you click the button) or not ...
Or you will allways override your data.
protected void Page_Load(object sender, EventArgs e)
{
if (!PostBack)
{
string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["proekt"].ConnectionString;
string sql = "SELECT id,title,image,text FROM home WHERE id in (1,2,3) order by id";
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
conn.Open();
search for datareader -> and use it here ... Save the returning data into
the datareader and filter by ID and if its item/title etc like here and here
conn.Close();
}
}
}

Fisrt, I want to suggest that, in the Page_Load, you only open the sql connection once and execute all the commands while the connection is open and then close it at the end. This will make your page load faster.
Second, you could use asp linkbutton to create a postback when clicked. The syntax should look like this:
<asp:LinkButton ID="A1" runat="server" OnClick="box1_Click">
<span>Запази полето <img src="notification-tick.gif" width="12" height="12" /></span>
</asp:LinkButton>

Related

How to link anchor tag to c# function?

i want to link an tag to a c# function on the backend side. I tried looking up on the internet but im not getting very far.
Here is what I have so far:
<a asp-page="/Notifications" runat="server" onserverclick="RemoveCount" ><h5 class="font-italic text-left">Notifications </h5></a>
And this is the function in the backend which im trying to link
public void RemoveCount(object sender, EventArgs e) {
var cs = Database.Database.Connector();
using var con = new NpgsqlConnection(cs);
con.Open();
var sql = "TRUNCATE TABLE counter ";
using var cmd = new NpgsqlCommand(sql, con);
cmd.Prepare();
cmd.ExecuteNonQuery();
con.Close();
}

Duplicating records in c#

I am making a attendance system, and here is my problem now, after i searched for a name of a person and try to log him in for attendance, it is fine at first, after logging in the second name it is still fine. but once i tried to edit the login attendance of the first or second user, all the values in my datagridview(connected to my database) became duplicated. if i enter name1 for attendance in my week1 it is fine. name2 for attendance in week1 is still fine.
but if i edit the same name. or even go to the next week number, all of the saved values got duplicated based on my recent inputed name.
for inserting new records
SqlConnection cnn200 = new SqlConnection(connectionstring);
string sql200 = "SELECT * FROM attendance WHERE csign=#csign ";
cnn200.Open();
SqlCommand cmd200 = new SqlCommand(sql200, cnn200);
SqlDataReader rdr200;
cmd200.Parameters.AddWithValue("#csign", callsign);
rdr200 = cmd200.ExecuteReader();
if (rdr200.Read() == true)
{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "insert INTO attendance
(csign,name,week1)" + "VALUES" + "(#csign,#name,#week1)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "insert INTO attendance
(csign,name,week2)" + "VALUES" + "(#csign,#name,#week2)";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
and for updating
else{
SqlConnection cnn201 = new SqlConnection(connectionstring);
if (textBox89.Text == "1")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week1=#week1";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week1",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}
if (textBox89.Text == "2")
{
string sql201 = "UPDATE attendance SET
name=#name,csign=#csign,week2=#week2";
cnn201.Open();
SqlCommand cmd201 = new SqlCommand(sql201, cnn201);
cmd201.Parameters.AddWithValue("#name", namee);
cmd201.Parameters.AddWithValue("#csign", callsign);
cmd201.Parameters.AddWithValue("#week2",
comboBox1.Text);
cmd201.ExecuteNonQuery();
}`}
nica, I think I can help. What you are trying to do can be done easily with less coding lines. An entire DataGridView can be displayed, edited, deleted and have no duplicates by using a few more objects
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace ADO_NET_Testbed
{
public partial class MainForm : Form
{
private SqlDataAdapter adapter;
private string connectionString = #"Data Source=Server;Persist Security Info=True;Password=password!;User ID=sooperuser;Initial Catalog=Database";
private string sqlcommand = #"SELECT OPID, LastName, FirstName, Title, PhoneOffice, PhoneCell, Email, Active, Admin, Tester, Educator, Developer FROM AuditUser";
private SqlCommandBuilder cmdBuilder = new SqlCommandBuilder();
private DataTable datatable = new DataTable();
private DataSet dataset = new DataSet();
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
adapter = new SqlDataAdapter(sqlcommand, connectionString);
adapter.Fill(dataset, "AuditUser");
dgvUsers.DataSource = dataset.Tables[0];
dgvUsers.Enabled = true;
this.Show();
}
private void btnCancel_Click(object sender, EventArgs e)
{
dataset.Clear();
dataset.Reset();
this.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
cmdBuilder.DataAdapter = adapter;
adapter.Update(dataset.Tables[0]);
this.Close();
}
}
}
As a quick rundown of what is going on, the SqlDataAdapter holds the four queries, but auto-creates three from the SELECT command. Using a SqlCommandBuilder enables the other three to be added, although the debugger will not show them as anything but NULL. The adapter.Fill() and adapter.Update() handle all the different commands based on the RowState of each row in the datagridview. "Cancel" is overkill seeing as this form is closed anyway.

C# button that would add text from one textbox into another textbox based on a SQL query

I am new to C# and need to create a little form application, that has two textboxes one that asks for a [File_ID] then when button is pressed send that number to a query and in another textbox display the output.
I have been playing around with it a bit, and have something like this. But it is not working. I am not sure if I should go on a different direction. I would REALLY appreciate your help.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace testing
{
public partial class Form1 : Form
{
String str,dr;
SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True");
SqlCommand cmd;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
str = "SELECT TOP 1,[Sender Name],[Subject] from [OLE DB Destination] WHERE [CHAT #] ='" + textBox1.Text + "'";
cmd = new SqlCommand(str, con);
// dr = cmd.ExecuteReader();
con.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
textBox1.Text = cmd.ExecuteScalar().ToString();
}
}
}
Your SQL query syntax is wrong it should rather be below. You have a extra , after TOP 1 .. remove that
SELECT TOP 1 [Sender Name],[Subject] from [OLE DB Destination] WHERE...
Again in your button click you are just creating the command cmd = new SqlCommand(str, con); but never executing it. and just closing the connection.
In textBox2_TextChanged event handler you are trying to execute the query but connection has already gone. I think it's time you should consider reading about ADO.NET
This should do the trick. A couple of things to note:
since the button is executing your sql and populating the 2nd textbox, there's no need for the textbox_changed event
Using string concatenation to append your variables to your sql query is bad practice and makes your code susceptible to Sql Injection. Instead, parameterize your sql inputs as shown in the code below.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string query = "SELECT TOP 1,[Sender Name],[Subject] "
+ " from[OLE DB Destination] WHERE[CHAT #] = :chatId ";
using (SqlConnection con = new SqlConnection("Data Source=USHOU2016\\USFi;Initial Catalog=HOU_2016_Project;Integrated Security=True"))
{
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("chatId", textBox1.Text); //use Sql parameters to protect yourself against Sql Injection!
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
reader.Read();
textBox2.Text = reader[0] + " " + reader[1]; //or however you want your output formatted
}
reader.close();
}
}
}

Random Generator To Use Values From SQL Server DB

I have an asp.net application which is a random generator of places.
At present I am the values sat in my code behind but I would like to move these into my SQL Server DB but I have no idea on how to do this. For reference I am using SQL Server Management Studio.
Is this possible or am I just over complicating it?
Code Behind
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
List<string> Eat = new List<string>();
Eat.Add("Chinese Buffet");
Eat.Add("Harvester");
Eat.Add("Frankie & Benny's");
Eat.Add("Hungry Horse");
Eat.Add("Blaize");
Eat.Add("Chiquito");
Eat.Add("Cafe Football");
Eat.Add("Nando's");
Random Place = new Random();
int Places = Place.Next(0, Eat.Count);
txtDestination.Text = Eat[Places];
}
View
<div class="row">
<div class="col-sm-3">
<asp:TextBox class="form-control" ID="txtDestination" runat="server" disabled></asp:TextBox>
</div>
<div class="col-sm-2">
<asp:Button class="btn btn-success" ID="BtnDecideForMe" runat="server" Text="Decide For Me" OnClick="BtnDecideForMe_Click" />
</div>
</div>
Code For Suggestion But Cant Get It Working
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
namespace PaydayLunchGenerator
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=DEV-116\\ONLINE;" +
"Initial Catalog=PaydayLunch;" +
"Integrated Security=True;";
conn.Open();
//using (SqlConnection conn = new SqlConnection(PaydayLunchConnectionString1))
using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.VarChar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place = Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
txtDestination.Text = place;
}
}
}
}
You can achieve this by creating a view in SQL server and loading that view into a dataset. That way you can select from the dataset and refresh the data whenever you require.
Populating Dataset
Note - You could even go a step further and create a stored procedure that will just give you a random value from the table on demand :)
Create a stored procedure with an output variable, then inside create a select like this
CREATE PROC sp_RandomPlace
#OutputVar nvarchar(100) OUTPUT
AS
SET #OutputVar = (select top 1 percent Place from [PlaceTable] order by newid())
Then in your c#
using(SqlConnection conn = new SqlConnection(ConnectionString ))
using(SqlCommand cmd = new SqlCommand("dbo.sp_RandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.Nvarchar).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place= Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
}
The code above is untested but you get the jist
With the thanks to Alec, i manged to get it working eventually using the following:
protected void BtnDecideForMe_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = "Data Source=DEV-116\\ONLINE;Initial Catalog=PaydayLunch;Integrated Security=True";
using (SqlCommand cmd = new SqlCommand("dbo.GetRandomPlace", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
// set up the parameters
cmd.Parameters.Add("#OutputVar", SqlDbType.VarChar, 25).Direction = ParameterDirection.Output;
// open connection and execute stored procedure
conn.Open();
cmd.ExecuteNonQuery();
// read output value from #OutputVar
string place = Convert.ToString(cmd.Parameters["#OutputVar"].Value);
conn.Close();
txtDestination.Text = place;
}
}

Populate drop down list from SQL Server database

I have an ASPX page that has a drop down on it.
<div>
<p>Pick a customer to show their order(s)</p>
<asp:DropDownList ID="customerSelect" AutoPostBack="true" runat="server" OnSelectedIndexChanged="customerSelect_SelectedIndexChanged"></asp:DropDownList>
</div>
I want the options in the drop down to be populated from a database of customer names.
Here is what my database looks like
Here is my code behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateDropDown();
customerSelect_SelectedIndexChanged(null, null);
}
}
public void populateDropDown()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [Orders]", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
customerSelect.DataSource = ddlValues;
customerSelect.DataValueField = "OrderID";
customerSelect.DataTextField = "CustomerName";
cmd.Connection.Close();
cmd.Connection.Dispose();
}
I've used this code before. So I must be missing something simple but I'm not sure what it is.
EDIT
I am getting no errors. The code compiles. But the drop down list remains blank.
Well, I think you forget to bind your dropdownlist like;
customerSelect.DataBind();
And use using statement to dispose your SqlCommand, SqlConnection and SqlDataReader instead of calling .Dispose() method manually.
using(SqlConnection con = new SqlConnection(connString))
using(SqlCommand cmd = con.CreateCommand())
{
...
...
using(SqlDataReader ddlValues = cmd.ExecuteReader())
{
...
}
}

Categories