SQlite local Database data has gone when application restart? - c#

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.

Related

Update SQL Query not working ASP.NET Web Application

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();
}
}

c# - insert new data from datagridview without textboxes

Is it possible to modify this update code to run insert commands to mysql? if there is, can I get some help? I'm planning to use the blank rows in DataGridView to insert new data.
private void updateTable(object sender, DataGridViewCellEventArgs e)
{
DataTable changes = ((DataTable)dataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)dataGridView1.DataSource).AcceptChanges();
}
}
I have this, but this requires a textbox though.
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace PointOfSale
{
public partial class Users : Form
{
MySqlCommand cmd;
MySqlDataAdapter adapt;
int ID = 0;
private string conn;
private MySqlConnection connect;
public Users()
{
InitializeComponent();
DisplayData();
}
private void db_connection()
{
try
{
conn = "Server=localhost;Database=phvpos;Uid=root;Pwd=;";
connect = new MySqlConnection(conn);
connect.Open();
}
catch (MySqlException e)
{
throw;
}
}
//Insert Data
private void btnInsert_Click(object sender, EventArgs e)
{
if (txtName.Text != "" && txtPassword.Text != "" && txtUsertype.Text != "")
{
db_connection();
cmd = new MySqlCommand("insert into accounts(username, password, usertype) values(#name,#password,#usertype)", connect);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
cmd.Parameters.AddWithValue("#usertype", txtUsertype.Text);
cmd.ExecuteNonQuery();
connect.Close();
MessageBox.Show("Record Inserted Successfully");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
db_connection();
DataTable dt = new DataTable();
adapt = new MySqlDataAdapter("select * from accounts", connect);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
connect.Close();
}
//Clear Data
private void ClearData()
{
txtName.Text = "";
txtPassword.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txtName.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txtPassword.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
txtUsertype.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
}
//Update Record
private void btnUpdate_Click(object sender, EventArgs e)
{
db_connection();
if (txtName.Text != "" && txtPassword.Text != "" && txtUsertype.Text != "")
{
cmd = new MySqlCommand("update accounts set username=#name,password=#password,usertype=#usertype where userid=#userid", connect);
cmd.Parameters.AddWithValue("#userid", ID);
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#password", txtPassword.Text);
cmd.Parameters.AddWithValue("#usertype", txtUsertype.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
connect.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");

C# Visual Studio - Outputting SQL table data to Datagridview

Apologies if this has been covered. The examples I seemed to find were more complicated than I need it to be
I'm trying to output the entire contents of an SQL table to a DatagridView when a button "Display All Records" is clicked
I'm having a bit of trouble, here is what I have so far
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
Here is all my code if you need to refer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
public MainWindow()
{
InitializeComponent();
establishConnection();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Boolean postSuccess = false;
if (validation() == true)
{
SqlCommand details = new SqlCommand("INSERT INTO Student (Firstname, LastName, MatriculationNo, GradeOne, GradeTwo, GradeThree) VALUES (#FirstName, #LastName, #MatriculationNo, #GradeOne, #GradeTwo, #GradeThree)", con);
details.Parameters.AddWithValue("#FirstName", firstnameTextbox.Text);
details.Parameters.AddWithValue("#LastName", lastnameTextbox.Text);
details.Parameters.AddWithValue("#MatriculationNo", matriculationnoTextbox.Text);
details.Parameters.AddWithValue("#GradeOne", Component1Textbox.Text);
details.Parameters.AddWithValue("#GradeTwo", Component2Textbox.Text);
details.Parameters.AddWithValue("#GradeThree", Component3Textbox.Text);
con.Open();
details.ExecuteNonQuery();
postSuccess = true;
if (postSuccess)
{
MessageBox.Show("Details entered succesfully!");
firstnameTextbox.Clear();
lastnameTextbox.Clear();
matriculationnoTextbox.Clear();
Component1Textbox.Clear();
Component2Textbox.Clear();
Component3Textbox.Clear();
}
else
{
MessageBox.Show("Data not entered succesfully, please check DB connection");
}
con.Close();
}
}
private void establishConnection()
{
try
{
con.Open();
System.Diagnostics.Debug.Print("Connected to SQL database");
connectionLabel.Content = "Connected to SQL Database";
con.Close();
}
catch (Exception)
{
connectionLabel.Content = "not connected to sql database";
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
firstnameTextbox.Clear(); //Clears the first name textbox
lastnameTextbox.Clear(); //Clears the last name textbox
matriculationnoTextbox.Clear(); //Clears the Matriculation Number textbox
Component1Textbox.Clear(); //Clears the component one textbox
Component2Textbox.Clear(); //Clears the component two textbox
Component3Textbox.Clear(); //Clears the component three textbox
}
private Boolean validation()
{
if (!Regex.Match(firstnameTextbox.Text, "^[A-Z][a-zA-Z]*$").Success)
{
MessageBox.Show("Please Enter a valid First Name");
firstnameTextbox.Clear();
return false;
}
else
{
return true;
}
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
con.Open();
string sql = #"DELETE FROM Student;"; //Deleting all from Student table
SqlCommand purge = new SqlCommand(sql, con);
MessageBox.Show("Are you sure you want to purge the entire contents of the database?"); //Prompting user to make sure they want to delete
purge.ExecuteNonQuery(); //Execute purge query
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
}
}
}
Any help would be much appreciated, thank you
Just fill DataTable with your table and bind it to GridView.DataContext.
Like so:
First Add DataGrid in XAML editor <DataGrid Name="customDataGrid" ItemsSource="{Binding}">
then Code behind:
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable table = null;
string query = "select * from student";
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
table = new DataTable();
adapter.Fill(table);
}
}
}
catch (Exception ex)
{
//handle caught exception
}
if (table != null)
{
customDataGrid.DataContext = table.DefaultView;
}
}
}
}
Binding part: customDataGrid.DataContext = table.DefaultView;
try this....
private void Button_Click_2(object sender, EventArgs e)
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
DataTable dt = new DataTable();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dt);
con.Close();
da.Dispose();
dataGridView1.DataSource = dt;
}
MySqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from student";
try
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
con.Close();
Try this

The SelectCommand property has not been initialized before calling 'Fill'. in WinForm

I am building a windows application using C#. In my login form, I'm getting Select Command property has not been initialized before calling fill method.
Here is the code:
public partial class frmlogin : Form
{
SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=loginerror;Integrated Security=True");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter();
public frmlogin()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = con;
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "select * from login where username='" + txt1.Text + "' and password='" + txt2.Text +"'";
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
frmmain main = new frmmain();
main.Show();
}
else
{
MessageBox.Show("Please enter correct name and passowrd", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
You have to specify select command of SqlDataAdapter before filling your table. You are not doing it. Your SqlCommand object is not connected in any way to your SqlDataAdapter.
adp.SelectCommand=cmd;
Another way to accomplish would be to simply pass the SQLCommand as an argument into your data adapter as follows -
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
SQL Data Adapter interacts with the data table. It is used to fill the Data Table from SQL Server DataBase. Before, filling the Data Table, the Data Adapter should know the command it is going to execute. So we have to fill the object of SQL Command Type i.e
SqlDataAdapter da = new SqlDataAdapter(cmd);
Here cmd is the object of SQL Command.
Now, the Data Adapter will know which command to execute before filling the data table.
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 Employees_Details_Management_System
{
public partial class ShowEmpDtlsFrm : Form
{
SqlConnection con = new SqlConnection(#"Data Source = (local); Initial Catalog = sp_emp; Integrated Security = True");
public SqlCommand cmd { get; private set; }
// private SqlCommand cmd;
public ShowEmpDtlsFrm()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
ShwEmpDtlsLbl.Text = "Employee Database Management";
comboBox1.Text = "Click";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DataGridChk()//Check if DataGrid is empty or not
{
if (dataGridView1.RowCount == 1)
{
dataGridView1.Visible = false;
MessageBox.Show("The Given " + comboBox1.Text+ " is Invalid \nEnter Valid " + comboBox1.Text);
}
}
public void DbDataFetch(String Qry)//For Fetching data from database
{
SqlCommand cmd = new SqlCommand(Qry, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
dataGridView1.DataSource = ds.Tables["emp"].DefaultView;
DataGridChk();
}
public void SrchBtn_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "Employee ID" || comboBox1.Text == "Department ID" || comboBox1.Text == "Manager ID")
{
if (textBox1.Text != "")
{
con.Open();
dataGridView1.Visible = true;
if (comboBox1.Text == "Employee ID")
{
string Qry = "select * from emp where emp_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Department ID")
{
string Qry = "select * from emp where dep_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Manager ID")
{
string Qry = "select * from emp where manager_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
con.Close();
}
else
{
MessageBox.Show("Please Enter the ID...");
}
}
else
{
MessageBox.Show("Choose Valid Option...");
}
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
EmpDtlsFrm edf = new EmpDtlsFrm();
edf.Show();
this.Hide();
}
}
}

How to display data from database into textbox, and update it

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();
}

Categories

Resources