Using Visual Studio/ Windows Forms, I am trying to write data to a SQLite DB.
The Event handler for the "submit" button is supposed to take the information in the relevant textboxes and write them to the corresponding fields in the DB.
The database connection and location is handled in the dbConnect class, and works as the login form works.
When the submit button is clicked however, nothing happens, no error message, nothing.
Can you see anything glaring?
private void button2_Click(object sender, EventArgs e)
{
try
{
//write new customer data to db
using (SQLiteConnection dbcon = new SQLiteConnection(conString))
{
dbcon.ConnectionString = dbConnect.source;
string sql;
{
sql = "INSERT INTO guest(forename,surname,telnumber,email,address)"
+ " Values(#f,#l,#tel,#em,#ad)";
}
using (SQLiteCommand cmd = new SQLiteCommand(sql, dbcon))
{
cmd.Parameters.AddWithValue("f", foreTB.Text);
cmd.Parameters.AddWithValue("l", surTB.Text);
cmd.Parameters.AddWithValue("tel", telTB.Text);
cmd.Parameters.AddWithValue("em", emailTB.Text);
cmd.Parameters.AddWithValue("ad", addTB.Text);
//perform db operation
dbcon.Open();
cmd.ExecuteNonQuery();
dbcon.Close();
}
}
//display relevant action feedback message
{
showlabel("New Customer Added OK", 4000);
}
}
catch (Exception ex)
{
Console.WriteLine("An error occurred: '{0}'", e);
}
}
Related
I'm creating a Bus Ticket booking system. I have created a database called traveller and two tables named Useriden and BusDB respectively. In the aspx.cs file(Sign Up page), I'm checking for duplicate usernames but it simply navigates to the next page
I've tried everything but I'm unable to resolve this issue. I'm not getting any errors or warnings.
protected void BtnConfirmSignup_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=(localdb)\\MSSQLlocalDB;Initial Catalog=traveller;Integrated Security=True;Pooling=False");
SqlCommand cmd;
SqlDataReader read;
/*DEBUG: Prevent duplicate usernames*/
try
{
Session["user"] = TxtUsrName.Text;
Session["pass"] = TxtPsswd.Text;
Session["email"] = TxtEmail.Text;
cmd = new SqlCommand("select Name from Useriden",con);
con.Open();
read = cmd.ExecuteReader();
while (read.Read()) {
if ((read["Name"].ToString()).Equals(TxtUsrName.Text))
{
throw new Exception("Invalid Username");
}
else
{
Response.Redirect("SignUpNext.aspx");
}
}
}
catch (Exception ex) {
LabelUserName.Visible = true;
LabelUserName.Text = ex.Message;
con.Close();
ViewState["Caption"]=ex.Message;
}
}
On clicking the confirm button, it should check for duplicate usernames. I already have one record with the name "Faf" in my table Useriden. When I try to sign up using the same username, it's not throwing an exception instead it navigates to SignUp.aspx.
The duplicate check is only valid if there's one record. I'll modify the logic so that it works for more than record but right now, it's not even working for a single record.
I'm creating a windows application using C# whereby I'm accessing an empty Access database which contains two tables: Provinces and Locations. I'm working on the form that just deals with the Provinces table which looks like this:
This is a subform. When it is open, I can insert/update records etc. Whenever I make a change, I click on the Load Table button to display the changes in the DataGridView object.
If I close this subform and show it again, I can click on the Load Table button and recall all the data for display in the DataGridView object. However, if I close down the application altogether, then I lose all my data. I prove this by double clicking the database file to launch it in Access where I can see that the data is definitely gone. This has become a mystery as I can't figure out why the data doesn't persist in the file. Please advise.
Below is the code for the form. You can see from my methods that I'm careful to close the connection object each and every time I perform a function. So I'm at a loss as to why I keep losing the data on application close?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GTI_Taxi_Pricing
{
public partial class frmProv : Form
{
private OleDbConnection connection = new OleDbConnection();
public frmProv()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TaxiDB.accdb;Persist Security Info=False;";
}
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
String query = "SELECT * FROM Provinces;";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (txtName.Text == "")
{
MessageBox.Show("The name field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "INSERT INTO Provinces (name) VALUES ('" + txtName.Text + "')";
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
connection.Close();
}
catch(Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnNewRecord_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtName.Text = "";
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (txtID.Text == "")
{
MessageBox.Show("The id field must have a value.");
return;
}
if(txtName.Text == "")
{
MessageBox.Show("The name field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "UPDATE Provinces SET name='" + txtName.Text + "' WHERE id=" + txtID.Text + ";";
command.ExecuteNonQuery();
MessageBox.Show("Data Update Successful.");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (txtID.Text == "")
{
MessageBox.Show("The id field must have a value.");
return;
}
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "DELETE FROM Provinces WHERE id=" + txtID.Text + ";";
command.ExecuteNonQuery();
MessageBox.Show("Record Deleted Successfully.");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex);
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if(e.RowIndex >= 0)
{
DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
txtID.Text = row.Cells[0].Value.ToString();
txtName.Text = row.Cells[1].Value.ToString();
}
}
}
}
This is a common scenario with file based database (or attached database files)
Your connection string refers to the database without using any path.
This means that your database is located in the same directory where your application runs.
You don't have any problem inserting, modifying or deleting data but you loose everything when you restart the app from INSIDE a Visual Studio Debug Session.
Now, if you look at your project files you probably have the database file listed between the other files. Between the properties of this database file you will notice the property Copy to the Output directory and its value set to Copy Always.
This means that every time you restart your application from inside the Visual Studio environment that file is copied from the project folder to the output directory (usually BIN\DEBUG or BIN\x86\DEBUG) but this destroys the database used in the previous run removing the data inserted modified or deleted
Change the property Copy to Output Directory to Copy Never or Copy if Newer
However Copy If Newer presents another problem with MS-Access. If you open the database file located in your project directory using Access o using the Server Connection window of Visual Studio the file is immediately modified also if you don't change anything and thus the Copy If Newer will execute the copy to the output directory
I need to add value to table sales(acnum,scriptname,shares_bought) from transac(acnum,scriptname,Quantity,Price) using c# in visual studio 2008. I am using the code shown below, but it is not inserting value into sales database.
It is not showing any error or exception but its not updating sales table also.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
Con.Open();
string insertsale = "INSERT INTO sales(acnum, scriptname, shares_bought) select acnum,scriptname,Quantity from transac";
SqlCommand cmd = new SqlCommand(insertsale, Con);
cmd.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
Response.Write("error" + ex.ToString());
}
}
The problem was that I had used PostUrl for the button click . . so i think it was redirecting to the nextpage without processing the code. Now its fixed .
i'm a newbie in .NET and C# field.
I'm creating a Registration page to a website im working on.
i keep getting an error when registering to a website i'm creating. When entering my details, it doesn't register me to the database.
I created the a table in the database(i created a connectionString), and yet i cannot register - i get an exception that says "error,please try registering again" (as i did).
Does someone know what am i doing wrong?! Thanks!
here's my code and images:
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;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from Table where Username='" + TextBox1Username.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
// int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
/* if (temp == 1)
{
Response.Write("username already exists");
} */
}
}
protected void TextBox2_TextChanged(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RegisConnectionString"].ConnectionStr ing);
con.Open();
string insCmd = "Insert into Table (Username, Password, EmailAddress,Fullname, City) values (#Username, #Password, #EmailAddress, #Fullname, #City)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error,please try registering again");
}
}
}
image:
[URL=http://imageshack.us/photo/my-images/4/os6b.jpg/][IMG=http://img4.imageshack.us/img4/2526/os6b.jpg][/IMG][/URL]
Uploaded with [URL=http://imageshack.us]ImageShack.us[/URL]
you are missing fullname in your parameter and you have password twice.fix that and run it again.
Also, in your catch block.. you should use exception message to debug or log somewhere where you can see the error clearly. the way you have it right now gives the error you typed. not actual message.
here is link where they are discussing about sqlexception. might be good idea to catch that.
SqlException catch and handling
You pass two times the password parameter in the insert query. The second one is in place of the #fullname parameter.
This will cause your insert command to fail because you don't provide the #fullname parameter expected by the query.
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#Username", TextBox1Username.Text);
insertUser.Parameters.AddWithValue("#Password", TextBox2Password.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBox4Email.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBox???????.Text); //<- Get from the correct textbox
insertUser.Parameters.AddWithValue("#City", TextBox6City.Text);
You could have found this problem yourself if, inside the catch, you had added the er.Message to your Response
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("Login.aspx");
}
catch (Exception er)
{
Response.Write("error: " + er.Message + " ,please try registering again");
}
I'm making a system for checking bookings online using a booking ID, I've done all the code and when I run my application on the web browser it appears to disconnect with the message "Problem loading page"
this is the code used for checking the system when pressing the button
protected void Button1_Click(object sender, EventArgs e)
{
int custval = 70757;
if (BookID.Text == Convert.ToString(custval))
{
try
{
SqlConnection GuestBookings = new SqlConnection("Data Source=dell-vostro;Initial Catalog=HotelConference;Persist Security Info=True;User ID=website_application_testing;Password=***********");
SqlCommand sc = new SqlCommand();
sc.Connection = GuestBookings;
GuestBookings.Open();
sc.CommandText = ("SELECT CustomerFirstName, CustomerLastName FROM tblBookingGuests WHERE BookingID="+BookID.Text+")");
sc.ExecuteNonQuery();
GuestBookings.Close();
}
catch (Exception ex)
{
}
}
}