Here is the code of my .aspx page,
When I click on update it runs the page doesn't show any errors and the row is not updated in my blog table.
The exception doesn't display anything, and i have a row with the id in my table.
The select command in the Page_Load() works perfectly.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Blog
{
public partial class update : System.Web.UI.Page
{
SqlConnection connection = new SqlConnection(##################);
protected void Page_Load(object sender, EventArgs e)
{
string id = Request.QueryString["id"];
string sql = "select * from blog where Id=#id";
SqlCommand sqlCommand = new SqlCommand(sql,connection);
sqlCommand.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader dataReader = sqlCommand.ExecuteReader();
while (dataReader.Read())
{
DropDownListCategory.SelectedIndex = DropDownListCategory.Items.IndexOf(DropDownListCategory.Items.FindByText(dataReader["category"].ToString().Trim()));
TextBoxTitle.Text = dataReader["title"].ToString();
TextBoxDesc.Text = dataReader["description"].ToString();
}
connection.Close();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
LabelDate.Text = DateTime.Now.ToString();
}
protected void Update_Click(object sender, EventArgs e)
{
try
{
int id = Convert.ToInt32(Request.QueryString["id"].Trim());
string sql2 = "UPDATE blog SET title = #title , category = #category , description = #description , posteddate = #posteddate WHERE Id=#id";
connection.Open();
SqlCommand sqlCommand2 = new SqlCommand(sql2, connection);
sqlCommand2.Parameters.AddWithValue("#id", id);
sqlCommand2.Parameters.AddWithValue("#title", TextBoxTitle.Text);
sqlCommand2.Parameters.AddWithValue("#category", DropDownListCategory.SelectedItem.Text.ToString());
sqlCommand2.Parameters.AddWithValue("#description", TextBoxDesc.Text);
sqlCommand2.Parameters.AddWithValue("#posteddate", DateTime.Now.ToString());
sqlCommand2.ExecuteNonQuery();
}
catch(Exception ex)
{
Label1.Text = ex.Message;
}
connection.Close();
//Response.Redirect("Default.aspx");
}
}
}
Added a if(!IsPostBack){} now works fine, Thank you
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string id = Request.QueryString["id"];
string sql = "select * from blog where Id=#id";
SqlCommand sqlCommand = new SqlCommand(sql, connection);
sqlCommand.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader dataReader = sqlCommand.ExecuteReader();
while (dataReader.Read())
{
DropDownListCategory.SelectedIndex = DropDownListCategory.Items.IndexOf(DropDownListCategory.Items.FindByText(dataReader["category"].ToString().Trim()));
TextBoxTitle.Text = dataReader["title"].ToString();
TextBoxDesc.Text = dataReader["description"].ToString();
}
connection.Close();
}
}
Related
I am creating a basic registration page using ASP.NET websites and C# and am trying to link the logins to a database I have created in Visual Studio 2017 and am constantly getting the error -
'System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Data.Common.DbCommand.ExecuteScalar(...) returned null.
and cannot understand why, code below any help appreciated.
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "SELECT * FROM [Table] WHERE UserName='" + TextBoxUN.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists, please enter a different username");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertQuery = "INSERT INTO Table (UserName,Email,Password,Country) values(#Uname ,#email , #password ,#country)";
SqlCommand com = new SqlCommand(insertQuery, conn);
com.Parameters.AddWithValue("#Uname" , TextBoxUN.Text);
com.Parameters.AddWithValue("#email" , TextBoxEmail.Text);
com.Parameters.AddWithValue("#password" , TextBoxPass.Text);
com.Parameters.AddWithValue("#country" , DropDownListCountry.SelectedItem.ToString());
com.ExecuteNonQuery();
Response.Redirect("Manager.aspx");
Response.Write("Registration Successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("Error:" + ex.ToString());
}
}
}```
If you want to check if user exists, there's no need in ExecuteScalar() with value:
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
when user doesn't exist, com.ExecuteScalar() returns null and you have a problem.
Code
private static bool UserExists(string userName) {
if (null == userName)
return false;
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString)) {
conn.Open();
//DONE: parametrized query
//DONE: 1 instead of * - we don't want all columns to be returned
string sql =
#"select 1
from [Table]
where UserName = #userName";
using (SqlCommand com = new SqlCommand(sql, conn)) {
com.Parameters.Add("userName", SqlDbType.VarChar).Value = userName;
// user exists if cursor is not empty (we have at least one record)
return com.ExecuteScalar() != null;
}
}
}
protected void Page_Load(object sender, EventArgs e) {
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (IsPostBack && UserExists(TextBoxUN.Text))
Response.Write("User already exists, please enter a different username");
}
I am developing windows application .Net in C#
DB stored inside the C# Application ".....\SQliteExample\SQliteExample\bin\Debug\MyDatabase.sqlite"
I can insert,update ,view and Delete to the table with the above code and view its contents in another activity with no troubles at all. However, when I restart the application I found that what I have inserted data before I restart the application has gone!
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.SQLite;
namespace SQliteExample
{
public partial class Form1 : Form
{
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
public Form1()
{
InitializeComponent();
SQLiteConnection.CreateFile("MyDatabase.sqlite");
connection.Open();
string sql = "create table Employee1 (EmpID int,EmpName varchar(20), age int,Salary int,Phone int , Address Varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "insert into Employee1 (EmpID,EmpName,Age,Salary,Phone,Address) values (?,?,?,?,?,?)";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", textBox1.Text);
command.Parameters.AddWithValue("EmpName", textBox2.Text);
command.Parameters.AddWithValue("Age", textBox3.Text);
command.Parameters.AddWithValue("Salary", textBox4.Text);
command.Parameters.AddWithValue("Phone", textBox5.Text);
command.Parameters.AddWithValue("Address", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Saved");
Clear();
View();
}
private void Clear()
{
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
}
private void View()
{
string sql3 = "select * from Employee1 order by EmpID asc";
SQLiteCommand command3 = new SQLiteCommand(sql3, connection);
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(command3);
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
View();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "delete from Employee1 where EmpID = ?";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", int.Parse(textBox1.Text));
command.ExecuteNonQuery();
connection.Close();
Clear();
View();
}
else
{
MessageBox.Show("Please Enter EmpID");
}
}
}
}
Thanks in Advance,
On recompilation you recreate the database file and recreate the table "employee". Therefore all your previous data is lost.
In this code I read the patient infos from database with patientId parameter passed with URL. Then I fill the 5 textboxes with this values at Page_Load. But at Update_Click the code can't reach the updated textbox values, it reads only initial values of the textboxes. I saw it at debugging. No problems at database level. When I remove the Page_Load code and leave the textboxes empty initially, the code from Update_Click can reach the user input and update the values. What is the problem?
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
public partial class admin_Testadmin : System.Web.UI.Page
{
Patient patient = new Patient();
protected void Page_Load(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.select_patient, cn);
command.CommandType = CommandType.StoredProcedure;
int pid = int.Parse(Request.QueryString["patientId"]);
command.Parameters.AddWithValue("pid", pid);
command.Parameters["pid"].Direction = ParameterDirection.Input;
cn.Open();
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
txtName.Text = patient.Name = (String)reader[0];
txtSurname.Text = patient.Surname = (String)reader[1];
txtFathersname.Text = patient.Fathersname = (String)reader[2];
txtStatus.Text = patient.Status = (String)reader[3];
txtSuccessDescription.Text = patient.SuccessDescription = (String)reader[4];
patient.Id = (int)reader[5];
}
reader.Close();
cn.Close();
}
}
protected void Update_Click(object sender, EventArgs e)
{
String cs = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
using (MySqlConnection cn = new MySqlConnection(cs))
{
MySqlCommand command = new MySqlCommand(StoredProcedures.update_patient, cn);
command.CommandType = CommandType.StoredProcedure;
patient.Name = txtName.Text.Trim();
patient.Surname = txtSurname.Text.Trim();
patient.Fathersname = txtFathersname.Text.Trim();
patient.Status = txtStatus.Text.Trim();
patient.SuccessDescription = txtSuccessDescription.Text;
patient.Id = int.Parse(Request.QueryString["patientId"]);
command.Parameters.Add("pname", MySqlDbType.VarChar).Value = patient.Name;
command.Parameters.Add("psurname", MySqlDbType.VarChar).Value = patient.Surname;
command.Parameters.Add("pfathersname", MySqlDbType.VarChar).Value = patient.Fathersname;
command.Parameters.Add("pstatus", MySqlDbType.VarChar).Value = patient.Status;
command.Parameters.Add("psuccessdescription", MySqlDbType.Text).Value = patient.SuccessDescription;
command.Parameters.AddWithValue("pid", patient.Id);
command.Parameters["pid"].Direction = ParameterDirection.Input;
cn.Open();
if (command.ExecuteNonQuery() > 0)
{
ResultLabel.Text = "";
ResultLabel.Text = "Update success";
}
cn.Close();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
// Rest of your code here
}
In the case of a postback, you do not want to overwrite what the user typed.
Here are some docs about the ASP.NET page life cycle.
I'm trying to make an agenda facility for my winform project. I want to display database records on textBox for specific date when user chose date on monthCalendar control. Below you can see my db table design, my winform design and my code and exception message that i'm getting. How can i fix this?
*ps: no need to suggest on using parametrized queries. i can and i will change it eventually
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace EKS
{
public partial class Agenda : Form
{
public Agenda()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
panel1.BackColor = Color.FromArgb(100, 88, 55, 55);
}
private void button1_Click(object sender, EventArgs e)
{
try {
string myQuery = "insert into agenda (input_agenda, input_date) values ('"+textBox1.Text.ToString()+"', '"+ monthCalendar1.SelectionStart +"')";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = myQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("agenda updated");
}
catch (Exception x) {
MessageBox.Show(x.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try {
string deleteQuery = "DELETE FROM agenda WHERE input_date = '" + monthCalendar1.SelectionStart +"'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
SqlCommand myComm = new SqlCommand();
myComm.Connection = myConn;
myComm.CommandText = deleteQuery;
myConn.Open();
myComm.ExecuteNonQuery();
myConn.Close();
MessageBox.Show("delete succeeded");
}
catch(Exception x){
MessageBox.Show(x.ToString());
}
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
GetAgendaDetails(e.Start.Date);
}
private void GetAgendaDetails(DateTime x){
string myQuery = "select input_agenda from agenda where input_date = '" + x.Date.ToString() + "'";
SqlConnection myConn = new SqlConnection();
myConn.ConnectionString = "Data Source=localhost; database=EKS; uid=sa; pwd=123; connection lifetime=20; connection timeout=25; packet size=1024;";
try {
myConn.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(myQuery,myConn);
myReader = myCommand.ExecuteReader();
while (myReader.Read()) {
textBox1.Text = myReader.GetString(100);
}
myConn.Close();
}
catch(Exception z){
MessageBox.Show(z.ToString());
}
}
}
}
Use DateSelected event of MonthCalendar control, Which will be fired when user selects a date.
private void monthCalendar1_DateSelected(object sender, DateRangeEventArgs e)
{
AganedaInformation info = GetAgendaDetails(e.Start.Date);
}
Add a private method to query the database based on the passed selected date
Private AganedaInformation GetAgendaDetails(DateTime selectedDate)
{
//Add logic to query the database with the selected date and return the information
}
I can display my data in my textbox, dropdownlist after retrieve data from sql database, but when i proceed with my update button, the information edited in the textbox or dropdownlist wouldn't update into the database. I tried to remove the code in page load, and re-key in all the data manually, it can be update. All I want is retrieve data from database and display it in the textbox, and it can be update into the database after make some changes from the textbox. Can someone help me on this? Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class UpdateCustomerDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True");
SqlCommand cmd = new SqlCommand("UPDATE customer_registration SET password = #password, retypepassword = #retypepassword, gender = #gender, birth = #birth, address = #address, city = #city, country = #country, postcode = #postcode, email = #email, carno = #carno where username='" + Session["username"] + "'", con);
con.Open();
cmd.Parameters.AddWithValue("#password", TextBoxPassword.Text);
cmd.Parameters.AddWithValue("#retypepassword", TextBoxRPassword.Text);
cmd.Parameters.AddWithValue("#gender", DropDownListGender.Text);
cmd.Parameters.AddWithValue("#birth", DropDownListDay.Text + DropDownListMonth.Text + DropDownListYear.Text);
cmd.Parameters.AddWithValue("#address", TextBoxAddress.Text);
cmd.Parameters.AddWithValue("#city", TextBoxCity.Text);
cmd.Parameters.AddWithValue("#country", DropDownListCountry.Text);
cmd.Parameters.AddWithValue("#postcode", TextBoxPostcode.Text);
cmd.Parameters.AddWithValue("#email", TextBoxEmail.Text);
cmd.Parameters.AddWithValue("#carno", TextBoxCarno.Text);
cmd.ExecuteNonQuery();
con.Close();
if (IsPostBack)
{
Response.Redirect("UpdateSuccess.aspx");
}
}
Wrap your all statements in !IsPostBack condition on page load.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// all statements
}
}
This will fix your issue.
The answer is .IsPostBack as suggested by #Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load
private void PopulateFields()
{
using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
{
DataTable dt = new DataTable();
con1.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
TextBoxPassword.Text = (myReader["password"].ToString());
TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
DropDownListMonth.Text = (myReader["birth"].ToString());
DropDownListYear.Text = (myReader["birth"].ToString());
TextBoxAddress.Text = (myReader["address"].ToString());
TextBoxCity.Text = (myReader["city"].ToString());
DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
TextBoxPostcode.Text = (myReader["postcode"].ToString());
TextBoxEmail.Text = (myReader["email"].ToString());
TextBoxCarno.Text = (myReader["carno"].ToString());
}
con1.Close();
}//end using
}
Then call it in your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
PopulateFields();
}
}
protected void Page_Load(object sender, EventArgs e)
{
DropDownTitle();
}
protected void DropDownTitle()
{
if (!Page.IsPostBack)
{
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
SqlConnection con = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataReader reader;
try
{
ListItem newItem = new ListItem();
newItem.Text = "Select";
newItem.Value = "0";
ForumTitleList.Items.Add(newItem);
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem newItem1 = new ListItem();
newItem1.Text = reader["ForumTitles"].ToString();
newItem1.Value = reader["ForumTitlesID"].ToString();
ForumTitleList.Items.Add(newItem1);
}
reader.Close();
reader.Dispose();
con.Close();
con.Dispose();
cmd.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
Populate the text box values in the Page Init event as opposed to using the Postback.
protected void Page_Init(object sender, EventArgs e)
{
DropDownTitle();
}