Inserting Data From C# Form Into Linked Database? - c#

I'm building an application using C# and have decided to go with a windows Form. The goal is to have a user register and be able to login with their login credentials they set up in the registration form.
Registration Form:
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
connetionString = #"Data Source=THANATOS\SQLEXPRESS01;Initial Catalog=LoginDatabase;Integrated Security=True";
SqlConnection cnn = new SqlConnection(connetionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.Parameters.AddWithValue("#FirstName", first_NameTextBox.Text);
cmd.Parameters.AddWithValue("#LastName", last_NameTextBox.Text);
cmd.Parameters.AddWithValue("#Username", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#Password", passwordTextBox.Text);
cmd.Parameters.AddWithValue("#EmailAddress", email_AddressTextBox.Text);
cmd.Parameters.AddWithValue("#PhoneNumbers", passwordTextBox.Text);
cmd.CommandText = ("INSERT INTO UserRegiatration VALUES #FirstName, #LastName, #Username, #Password, #EmailAddress, #PhoneNumbers)");
try
{
cnn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You Have Been Registered!");
cnn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show("Please Try Again At A Later Time.");
}
}
This is what I have so far but I can't get the information the user enters in the text boxes to post to the database upon the button click event happening.
Any idea what I need to include or remove to improve this?

You missed a (:
INSERT into UserRegiatration VALUES
(#FirstName,#LastName,#Username,#Password,#EmailAddress,#PhoneNumbers)
^
Also, did you mean to write UserRegistration or is the table really called UserRegiatration?

In some cases you should have your table name should be surrounded in brackets.
It would look like:
INSERT into [UserRegiatration] VALUES
(#FirstName,#LastName,#Username,#Password,#EmailAddress,#PhoneNumbers)

I rewrote my tables and did some more research, it turns out, I was missing the part of the statement which identified which specific columns the information was supposed to be inserted into. This is what is now working for me. Thanks for the guidance and the troubleshooting advice.
private void registerButton_Click(object sender, EventArgs e)
{
string connetionString = null;
connetionString = #"Data Source=THANATOS\SQLEXPRESS01;Initial Catalog=LoginDatabase;Integrated Security=True";
try
{
using (SqlConnection connection = new SqlConnection(connetionString))
{
if (connection.State == ConnectionState.Closed) // Checking connection status, if closed then open.
{
connection.Open();
this.Hide();
}
String query = "INSERT INTO dbo.[Table] (FirstName,LastName,Username,Password,Email,PhoneNum) VALUES (#FirstName,#LastName,#Username,#Password,#Email,#PhoneNum)";
using (SqlCommand cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#FirstName", firstNameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#LastName", lastNameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Username", usernameTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Password", passwordTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#Email", emailTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
cmd.Parameters.AddWithValue("#PhoneNum", phoneNumTextBox.Text); // Syntax #"TableColumnName", TextBoxToGrabInfoFrom.Text
int result = cmd.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error inserting data into Database!"); // If error, display message.
}
}
}
catch (Exception ex)
{
string v = ex.Message;
throw ex;
}
}
private void phoneNumLabel_Click(object sender, EventArgs e)
{
}
}
}

Related

Why is my data not going to my SQL database when i click the button?

public partial class signupuser : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
// sign up button click event
protected void Button1_Click(object sender, EventArgs e)
{
//Response.Write("<script>alert('Testing');</script>");
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("INSERT INTO member_master_tbl(email, password, full_name, user_name, dob, account_status) VALUES(#email, #password, #full_name, #user_name, #dob, #account_status)", con);
cmd.Parameters.AddWithValue("#full_name", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#email", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("#user_name", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("#dob", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#account_status", "Pending");
cmd.ExecuteNonQuery();
con.Close();
Response.Write("<script>alert('Sign Up Successful. Go to User Login to Login.');</script>");
}
catch(Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "');</script>");
}
}
}
Here is the code, I am currently developing an asp.net web app and I am using a SQL server and trying to make a sign up page. I want the input from the user to be stored into the database when i click the button. All that happens right now is I click the button and the page refreshes, but no data is added to the database. I am also not getting the alert box saying "Sign Up Successful" so something must be going wrong. Ideas?
It is useless to check if connection open immediately after creation. Connection should be open for the shortest time possible. Just before you execute command object. You have to remove this code:
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
But you are opening the connection before you create cmd. You should use connection this way:
using (var con = new SqlConnection(strcon))
{
var cmd = new SqlCommand("INSERT INTO member_master_tbl(email, password, full_name, user_name, dob, account_status) VALUES(#email, #password, #full_name, #user_name, #dob, #account_status)", con);
cmd.Parameters.AddWithValue("#full_name", TextBox3.Text.Trim());
cmd.Parameters.AddWithValue("#email", TextBox2.Text.Trim());
cmd.Parameters.AddWithValue("#password", TextBox4.Text.Trim());
cmd.Parameters.AddWithValue("#user_name", TextBox5.Text.Trim());
cmd.Parameters.AddWithValue("#dob", TextBox1.Text.Trim());
cmd.Parameters.AddWithValue("#account_status", "Pending");
cmd.connection.Open();
if (cmd.ExecuteNonQuery()>= 1)
{
Response.Write("<script>alert('Sign Up Successful. Go to User Login
to Login.');</script>");
}
}

System.Threading.ThreadAbortException: Thread was being aborted.

What is wrong with my code? Pls Help. I keep getting error System.Threading.ThreadAbortException: Thread was being aborted.
This is my registration page c# code as below:
protected void submitbtn_Click(object sender, EventArgs e)
{
try
{
con.ConnectionString = "Data Source=DESKTOP-H7KQUT1;Initial Catalog=SAOS;Integrated Security=True";
con.Open();
string insertQuery = "insert into account" + "(username,password) values (#username,#password)";
SqlCommand cmd = new SqlCommand(insertQuery, con);
cmd.Parameters.AddWithValue("#username", TextBoxUN.Text);
cmd.Parameters.AddWithValue("#password", TextBoxPass.Text);
cmd.ExecuteNonQuery();
string insertQuery1 = "insert into parent" + "(Email,Contact,FName,LName,HomeAddress,Gender) values (#Email,#Contact,#FName,#LName,#HomeAddress,#Gender)";
SqlCommand cmd1 = new SqlCommand(insertQuery1, con);
cmd1.Parameters.AddWithValue("#Email", TextBoxEmail.Text);
cmd1.Parameters.AddWithValue("#Contact", TextBoxContact.Text);
cmd1.Parameters.AddWithValue("#FName", TextBoxFName.Text);
cmd1.Parameters.AddWithValue("#LName", TextBoxLName.Text);
cmd1.Parameters.AddWithValue("#HomeAddress", TextBoxHome.Text);
cmd1.Parameters.AddWithValue("#Gender", DropDownListGender.SelectedItem.ToString());
cmd1.ExecuteNonQuery();
MessageBox.Show("Registration is successfull!");
Response.Redirect("Login.aspx");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.ToString());
}
}
}
There is already an answer here: Why Response.Redirect causes System.Threading.ThreadAbortException?
This is caused by your Response.Redirect.
Also, it might be better to use:
using(SqlCommand cmd = new SqlCommand(insertQuery, conn)
{
// The sql command code here like parameters, etc.
}
Using dispose immediatly the SqlCommand. It might prevent error since you are using multiple SqlCommand.

Get error at com.ExecuteNonQuery() while adding data into table

I am trying to save data from web form in visual studio 2015(community edition). I am repeatedly getting error:
no mapping exists from object type. Error at line "com.ExecuteNonQuery()".
I have tried various solutions mention in this forum but none of them work for me. Please help. Thank you.
Error Messageļ¼š
My code
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string checkuser = "select count(*) from [Table] where Username='" + un.Text + "'";
SqlCommand com = new SqlCommand(checkuser, conn);
temp = Convert.ToInt32(com.ExecuteScalar().ToString());
if (temp == 1)
{
Response.Write("User already exists");
}
conn.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (temp == 0)
{
try
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertquery = "insert into [Table] (Designation, Username, Email, [Password]) values (#Designation, #Username, #Email, #Password)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.AddWithValue("#Designation", dn.SelectedItem.ToString());
com.Parameters.AddWithValue("#Username", un.Text);
com.Parameters.AddWithValue("#Email", em.Text);
com.Parameters.AddWithValue("#Password", pw.Text);
com.ExecuteNonQuery();
Response.Redirect("Managers.aspx");
Response.Write("Registration Successful");
conn.Close();
}
catch (Exception ex)
{
Response.Write("error :" + ex.ToString());
}
}
}
}
Your error seems to be in this line:
com.Parameters.AddWithValue("#Designation", dn.SelectedItem.ToString());
The AddWithValue do a mapping to determine what datatype is the object that you are passing to the method. That is failing.
Try this:
1) com.Parameters.Add("#Designation", SqlDbType.VarChar).Value = dn.SelectedItem.ToString();
2) If you want to keep using AddWithValue debug to see what is inside dn.SelectedItem.ToString()
Anyway, it is always preferable to use Add instead AddWithValue because of that typical problems as the one you are having right now. Take a look at this article: http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
As above error it seems due to object typecasting is invalid.
The major difference is the implicit conversion when using AddWithValue. If you know that your executing SQL query (stored procedure) is accepting a value of type int, nvarchar, etc, there's no reason in re-declaring it in your code.
For complex type scenarios (example would be DateTime, float), I'll probably use Add since it's more explicit but AddWithValue for more straight-forward type scenarios (Int to Int).
protected void Button1_Click(object sender, EventArgs e) {
if (temp == 0) {
try {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
conn.Open();
string insertquery = "insert into [Table] (Designation, Username, Email, [Password]) values (#Designation, #Username, #Email, #Password)";
SqlCommand com = new SqlCommand(insertquery, conn);
com.Parameters.Add("#Designation", SqlDbType.VarChar).Value = dn.SelectedItem.ToString();
com.Parameters.Add("#Username", SqlDbType.VarChar).Value = un.Text;
com.Parameters.Add("#Email", SqlDbType.VarChar).Value = em.Text;
com.Parameters.Add("#Password", SqlDbType.VarChar).Value = pw.Text;
com.ExecuteNonQuery();
Response.Redirect("Managers.aspx");
Response.Write("Registration Successful");
conn.Close();
} catch (Exception ex) {
Response.Write("error :" + ex.ToString());
}
}
}

I want to check whether given record is in database or not

I want to check whether given record is in database or not. It is showing error "Invalid Column name"
private void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=PC308433;Initial Catalog=SampleDatabase;Persist Security Info=True;User ID=sa;Password=adm23");
conn.Open();
SqlCommand sc = new SqlCommand("select USERNAME from QuizTable where USERNAME=" + UserNameTextbox.Text + "", conn);
string result =Convert.ToString(sc.ExecuteNonQuery());//I dont know to store the result of query here.Pls help me
if (result == UserNameTextbox.Text)
MessageBox.Show("Welcome");
else
MessageBox.Show("Please register");
conn.Close();
}
You have to use ExecuteReader() for it, ExecuteNonQuery() is only for insert,update and delete statements, and use Contructor which takes CommandBehaviour enum with SingleRow, as it should have one row per username:
SqlDataReader rdr = sc.ExecuteReader(CommandBehavior.SingleRow);
if(rdr.Read() && (rdr["USERNAME"].ToString() == UserNameTextbox.Text))
MessageBox.Show("Welcome");
}
SideNote:
You should be using parameterized queries, currently you are open to sql injection.
Try this,
private void SaveButton_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=PC308433;Initial Catalog=SampleDatabase;Persist Security Info=True;User ID=sa;Password=adm23");
conn.Open();
SqlCommand sc = new SqlCommand("select USERNAME from QuizTable where USERNAME=#USERNAME", conn);
sc.Parameters.AddWithValue(#USERNAME,'"+UserNameTextbox.Text+"');
SqlDataReader dr = sc.ExecuteReader();//Use this line
if (dr.HasRows)
MessageBox.Show("Welcome");
else
MessageBox.Show("Please register");
conn.Close();
}
First of all, make sure you have USERNAME column in QuizTable.
Here is a complete snippet for you-
Note: Your column USERNAME may create conflict with sql server reserve words. You should change it i.e. USER_NAME or LOGINNAME.
try
{
string userName = UserNameTextbox.Text.Trim();
using (SqlConnection conn = new SqlConnection("Your Conn String"))
{
string sql="select USERNAME from QuizTable where USERNAME=#USERNAME";
using (SqlCommand command = new SqlCommand(sql,conn))
{
command.Parameters.AddWithValue("#USERNAME", userName );
connection.Open();
Object IsFound = command.ExecuteScalar();
connection.Close();
if (IsFound == null)
{
//if not found
}
else
{
//if found
}
}
}
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
You need to put quotes around the value of the username parameter.
Also, don't use string concatenation to build sql statements. You are way open to injection attacks.
you can try this , because you use executenonquery () , here i think use ExecuteReader()
First you need to check 'username' in table then
Plesae try this....
SqlCommand sc = new SqlCommand("select USERNAME from QuizTable where USERNAME='" + UserNameTextbox.Text + "'", conn);

why isn't my c# insert query working?

what is the problem in my code?
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\extract step one\extract1.accdb;Persist Security Info=True";
String kerdes = Convert.ToString(textBox1.Text);
String valaszok = Convert.ToString(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(#kerdes, #valaszok)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.Add("#kerdes", OleDbType.VarChar).Value = kerdes;
cmd.Parameters.Add("#valaszok", OleDbType.VarChar).Value = valaszok;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
When I click the button it says:
Microsoft Office Access Database Engine
I made the database with Access. Any ideas?
OleDbCommand does not support named parameters - use ? instead:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");
I would also wrap both the command and connection in using blocks to ensure that the resources are disposed of properly.
You need to change your parameters to:
cmd.Parameters.AddWithValue("#kerdes", kerdes);
cmd.Parameters.AddWithValue("#valaszok", valaszok);
This needs to be done in addition to the above comment of changing your query to:
OleDbCommand cmd = new OleDbCommand("INSERT into extract (kerdes, valaszok) Values(?, ?)");

Categories

Resources