I have a couple of textboxes and some dropdownlists on a register page. When the user presses submit, I want the values to be validated and if they are correct I want to enter them in the database. My values are not being validated, even if I call validation manually and check whether they are valid or not. So my code is putting empty stuff in the DB...
protected void btn_registreren_Click(object sender, EventArgs e)
{
Validate();
if (Page.IsValid)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + Server.MapPath(#"\App_Data") + #"\Database11.accdb";
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Gebruikers(gebruikersnaam, geboortedatum, admin, wachtwoord) VALUES (#gebruikersnaam, #geboortedatum, #admin, #wachtwoord)";
cmd.Parameters.AddWithValue("#gebruikersnaam", txt_email.Text);
cmd.Parameters.AddWithValue("#geboortedatum", txt_dag.Text + "-" + ddl_maand.SelectedValue + "-" + txt_jaar.Text);
cmd.Parameters.AddWithValue("#admin", false);
cmd.Parameters.AddWithValue("#wachtwoord", txt_wachtwoord.Text);
try
{
conn.Open();
lblConnState.Text = "Connection is: " + conn.State.ToString();
cmd.ExecuteNonQuery();
}
catch (Exception exc)
{
lblConnState.Text = exc.Message;
}
finally
{
conn.Close();
lblConnState2.Text = "<br />Connection is: " + conn.State.ToString();
}
}
else
{
lblConnState2.Text = "not valid";
}
}
I tried: giving all fields, validators and submit button the same validation group. I tried doing this in the page load as well. Also looked around extensively on the internet but couldn't find what is wrong.
Related
Im trying to pass two parameters to my oracle package.
I can get the parameters, but it is not being passed into the database. Every time I run the application it fails to make a connection and goes straight to my try catch method.
Is there something I am doing wrong?
This is what I have so far:
using System.Data.OracleClient;
private void btnGetData_Click(object sender, EventArgs e)
{
GetOrders_OracleCon_GetData(Parameter1,Parameter2);
// when i output or add in a break i can see that the data does come into the Parameter values. However after that it doesnt go to my db
}
public void GetOrders_OracleCon_GetData(Int32 PM1, String PM2)
{
using (OracleConnection objConn = new OracleConnection("Data Source=" + dbcon + "; User ID=" + uid + "; Password=" + pass))
{
OracleCommand objCmd = new OracleCommand();
objCmd.Connection = objConn;
objCmd.CommandText = "PCK_Orders.get_data";
objCmd.CommandType = CommandType.StoredProcedure;
objCmd.Parameters.Add("pm1", OracleType.Number).Value = PM1;
objCmd.Parameters.Add("pm2", OracleType.VarChar).Value =PM2;
objCmd.Parameters.Add("selected_orders", OracleType.Cursor).Direction = ParameterDirection.Output;
try
{
objConn.Open();
OracleDataReader objReader = objCmd.ExecuteReader();
if (objReader.HasRows)
{
GetOrders_GetData(objReader);
btnCancel.Enabled = true;
}
else
{
Timer_ProgBar.Stop();
MessageBox.Show("Orders for this Datedoes not exist", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
GP_ClearAllFields("Y", "Y");
Timer_ProgBar_Initialize(0, "");
}
}
catch (Exception)
{
Timer_ProgBar.Stop();
MessageBox.Show("An error has occured");
// this is the error that i catch but im not sure what is causing it. am i missing something?
Timer_ProgBar_Initialize(0, "");
}
objConn.Close();
}
}
private void okbtn_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Desktop\GameMuseumManagementSystem.accdb";
try
{
conn.Open();
String Name = txtName.Text.ToString();
String Email = txtEmail.Text.ToString();
String Password = txtPassword.Text.ToString();
String my_query = "INSERT INTO Member(Member_Name,Member_Password,Member_Email)VALUES('" + Name + "','" + Email + "','" + Password + "')";
OleDbCommand cmd = new OleDbCommand(my_query, conn);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfuly...!");
}
catch (Exception ex)
{
MessageBox.Show("Failed due to" + ex.Message);
}
finally
{
conn.Close();
}
}
I am coding for the member registeration for a guest to use it. I have 3 pieces of data, member_name, member_ID, and password. I coded this and I get an error. My Visual Studio is connected to my MS Access database via the tools, after I write this code, the data can't be stored in Access, what should I do now? Any suggestion?
if (txtUsername.Text != "")
{
string q = "insert into info(Username) values ('" + txtUsername.Text.ToString() + "')";
dosomething(q);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
if (txtPassword.Text != "")
{
string a = "insert into info(Password) values ('" + txtPassword.Text.ToString() + "')";
dosomething(a);
txtUsername.Text = "";
}
else
{
MessageBox.Show("Please Complete the neccessary information");
}
private void dosomething(String q)
{
try
{
cn.Open();
cmd.CommandText = q;
cmd.ExecuteNonQuery();
cn.Close();
}
catch (Exception e)
{
cn.Close();
MessageBox.Show(e.Message.ToString());
}
}
Every time I run this it always show that error. I dont know how to fix it.
The code should record the data i put in a textbox to ms access database. plz helpp
Presumably, you've initialized cn somewhere by doing something like
cn = new SqlConnection();
You need to pass the connection string for the database to the constructor:
cn = new SqlConnection("your connection string here");
or set it sometime later, before you connect:
cn.ConnectionString = "your connection string here";
I made a project using c# and data base using access accdb and connected between them both. I made 2 buttons, first one to add new costumer, which works perfectly, and second one to update the data of the costumer (first name and last name), for some reason, the update button does not work, there is no error when I run the project, but after I click nothing happens...
private void button2_Click(object sender, EventArgs e)
{
connect.Open();
string cid = textBox1.Text;
string cfname = textBox2.Text;
string clname = textBox3.Text;
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
if (connect.State == ConnectionState.Open)
{
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
connect.Close();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
connect.Close();
}
}
else
{
MessageBox.Show("ERROR");
}
}
I believe your commandtext is where the trouble lies;
command.CommandText = "UPDATE Tcostumers SET cfname= " + cfname + "clname= " + clname + " WHERE cid = " + cid;
You require a comma between the set statements, and also as Gino pointed out the speechmarks.
Edit:
It's better than you use parameters for your variables, your current method is open to SQL injection, eg.
private void button2_Click(object sender, EventArgs e)
{
OleDbCommand command = new OleDbCommand(#"UPDATE Tcostumers
SET cfname = #CFName,
clname = #CLName
WHERE cid = #CID", connect);
command.Parameters.AddWithValue("#CFName", textBox2.Text);
command.Parameters.AddWithValue("#CLName", textBox3.Text);
command.Parameters.AddWithValue("#CID", textBox1.Text);
try
{
connect.Open();
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
try
{
command.ExecuteNonQuery();
MessageBox.Show("DATA UPDATED");
}
catch (Exception expe)
{
MessageBox.Show(expe.Source);
}
finally
{
connect.Close();
}
}
Its how I tend to format my code, so do as you will with it. Hope it helps.
It might be a stupid thing but...
you're updating strings not ints so try adding '' to your strings something like:
command.CommandText = "UPDATE Tcostumers SET cfname= '" + cfname + "' clname='" + clname + "' WHERE cid = " + cid;
//my sample code for edit/update
Table Name = StudentFIle
Fields = id,fname,lname
bool found = false;
OleDbConnection BOMHConnection = new OleDbConnection(connect);
string sql = "SELECT * FROM StudentFIle";
BOMHConnection.Open();
OleDbCommand mrNoCommand = new OleDbCommand(sql, BOMHConnection);
OleDbDataReader mrNoReader = mrNoCommand.ExecuteReader();
while (mrNoReader.Read())
{
if (mrNoReader["id"].ToString().ToUpper().Trim() == idtextbox.Text.Trim())
{
mrNoReader.Close();
string query = "UPDATE StudentFIle set fname='" +firstnametextbox.Text+ "',lname='"+lastnametextbox.Text+"' where id="+idtextbox.Text+" ";
mrNoCommand.CommandText = query;
mrNoCommand.ExecuteNonQuery();
MessageBox.Show("Successfully Updated");
found = true;
break;
}
continue;
}
if (found == false)
{
MessageBox.Show("Id Doesn't Exist !.. ");
mrNoReader.Close();
BOMHConnection.Close();
idtextbox.Focus();
}
...
using System.Data;
using System.Data.OleDb;
namespace accessloginapp
{
public partial class Ramen : Form
{
private OleDbConnection connection = new OleDbConnection();
public Ramen()
{
InitializeComponent();
connection.ConnectionString =
#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\...\Users.accdb;Persist Security Info=False;";
}
private void btn_Save_Click(object sender, EventArgs e)
{
try{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText =
"insert into userdata (Username,[Password]) values('" +
txt_Username + "','" + txt_Password + "')";
command.ExecuteNonQuery();
MessageBox.Show("Users added and saved");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error" + ex);
}
}
}
}
I'm sorry if I do not understand much, I'm fairly to new to this. When I save data such as username and password in my application, the data is inserted as what I input but with added text, Example: I would send the username "Mark" to be inserted, but when I go to look at my database, it is put in as "System.Windows.Forms.TextBox, Text: Mark". How can I change this to only inserting the Username I Input?
You need to use Text property of textbox control, to fetch the actual text stored:-
command.CommandText = "insert into userdata (Username,[Password])
values('" + txt_Username.Text + "','" + txt_Password.Text + "')";
Apart from this please note your query is open for SQL Injection attack.
So, you should use Parameterized query something like this:-
command.CommandText = "insert into userdata (Username,[Password])
values(?,?)";
command.Parameters.Add("?",OleDbType.VarChar,20).Value = txt_Username.Text;
and similarly add parameter for #Password.