This is my code for the insert, I got textboxes on my form and I write something inside but when pressing the button with executes the code below it shows an error by the (cmd.ExecuteNonQuery)
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
cn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype, patribute, role, role2, role3) VALUES (#Heroname, #Attacktype, #patribute, #role, #role2, #role3)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#Attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
textBox1.Clear(); textBox2.Clear();
textBox3.Clear(); textBox4.Clear();
textBox5.Clear(); textBox6.Clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
The second code snippet is my update code which shows same an error when trying to execute, same error by the execute non query
SqlDataReader reader = null;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
SqlCommand sda = new SqlCommand("SELECT * FROM Heroes ", cn);
cn.Open();
reader = sda.ExecuteReader();
while (reader.Read())
{
object Heroname = reader["heroname"];
listBox1.Items.Add(Heroname.ToString());
}
reader.Close();
cn.Close();
Please I need help and as quick as someone can, ty!
I think you receive this error, that because you using reserved word Role you should place It in brackets [].
cmd.CommandText = "INSERT INTO Heroes (Heroname, Attacktype,patribute,[role],role2,role3) VALUES (#Heroname, #Attacktype,#patribute,#role,#role2,#role3)";
I suggest to avoid that method of passing parameters, with
cmd.Parameters.AddWithValue("#Heroname", textBox1.Text);
you didn't specify datatype and length, that's correct ADO.NET will guess them but this is not happens always, instead of that try this method:
cmd.Parameters.Add("#Heroname", SqlDbType.VarChar, 50).Value = textBox1.Text;
for all of your parameters.
Was it a null reference exception?
Reading your code, I think you need to change SqlDataReader reader = null; to SqlDataReader reader = new SqlDataReader;
SqlConnection cn = new SqlConnection(global::dotasuka.Properties.Settings.Default.Database1ConnectionString);
try
{
SqlCommand cmd = new SqlCommand("INSERT INTO Heroes (heroname,attacktype,patribute,role,role2,role3) Values (#heroname,#attacktype,#patribute,#role,#role2,#role3) ", cn);
cn.Open();
cmd.Parameters.AddWithValue("#heroname", textBox1.Text);
cmd.Parameters.AddWithValue("#attacktype", textBox2.Text);
cmd.Parameters.AddWithValue("#patribute", textBox3.Text);
cmd.Parameters.AddWithValue("#role", textBox4.Text);
cmd.Parameters.AddWithValue("#role2", textBox5.Text);
cmd.Parameters.AddWithValue("#role3", textBox6.Text);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
This code worked now, inside my form i added a listbox and it does show the added row with its values! But closing form and checking inside database, it doesnt show that row? Whats wrong?
Related
I am making a project in C# Windows forms. So far I have figured out how to code a login form from YouTube but I don't know how to use the same method to make a sign up form. Here is the code below and I am hoping someone can help make the adjustments so it inserts the username and password into database instead for a user.
try
{
SqlConnection con= new SqlConnection("");
SqlCommand cmd = new SqlCommand("select * from tblLogin where username = #username and password = #password", con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
SqlDataAdapter da = New SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.fill(dt);
if(dt.Rows.Count>0)
{
MessageBox.Show("login successful");
}
}
catch(Exception ex)
{
MessageBox.Show("" + ex);
}
Incase I have copied the code wrong the link to the video is here: https://youtu.be/nh-fleqcds4
That should be your solution.
You have to insert your textbox values instead of select them.
try
{
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand("insert into tblLogin(username, password)values(#username, #password)", con);
cmd.Parameters.AddWithValue("#username", TextBox1.Text);
cmd.Parameters.AddWithValue("#password", TextBox2.Text);
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("" + ex);
}
This Tutorial is very helpful in my opinion
This is just a simple way of registering new account credentials. My problem is that whenever I click the save button, the data will be saved twice in the database.
Sample image of the double entry in the database.
using (SqlConnection con = new SqlConnection(conString))
{
try
{
string query = ("INSERT INTO Tbl_Staff (Name,pos,username,password) VALUES (#name,#pos,#username,#password)");
using (SqlCommand cmd = new SqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#name", textBox1.Text);
cmd.Parameters.AddWithValue("#pos", textBox4.Text);
cmd.Parameters.AddWithValue("#username", textBox2.Text);
cmd.Parameters.AddWithValue("#password", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
//MessageBox.Show(result.ToString());
// Check Error
if (result > 0)
MessageBox.Show("Credentials has been successfully added.","" ,MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You're calling ExecuteNonQuery() twice.
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
you excecute the query twice.
change:
con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();
to
con.Open();
int result = cmd.ExecuteNonQuery();
i am getting this error so often, i can't find out what's wrong in here?
con.Open();
String query = "INSERT INTO user (username,[password]) values(a,b)";
OleDbCommand cmd1 = new OleDbCommand(query, con);
cmd1.Parameters.AddWithValue("a",textBox1.Text);
cmd1.Parameters.AddWithValue("b", textBox2.Text);
cmd1.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
SqlParameters should start with # like #Name. try this:
con.Open();
String query = "INSERT INTO user (Username, [Password]) values(#Username, #Password)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("#Username",textBox1.Text);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("User Account Created");
this.Close();
Read Using Variables and Parameters
i write code that insert and delete some data with Microsoft Access database , i can insert the data but when i delete it i have an error "data-type-mismatch-in-criteria-expression" i don't know why !!! Any one help me ?
thanks in advance ;
private void Savebt_Click(object sender, EventArgs e)
{
//try
//{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\me\Library Store\Library Store\Store.accdb");
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Libarary ( ISBN, [Name], Gategory, Author, Cost, [Date]) " +
"VALUES ( #ISBN, #Name, #Gategory, #Author, #Cost, #Date) ";
cmd.Parameters.AddWithValue("#ISBN", ISBNTB.Text);
cmd.Parameters.AddWithValue("#Name", NameTB.Text);
cmd.Parameters.AddWithValue("#Gategory", GategoryTB.Text);
cmd.Parameters.AddWithValue("#Author", AuthorTB.Text);
cmd.Parameters.AddWithValue("#Cost", int.Parse(CostTB.Text));
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Book Added!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void sellbt_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\me\Library Store\Library Store\Store.accdb");
try
{
conn.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = " DELETE * FROM Libarary WHERE ISBN=#ISBN AND [Name]=#Name AND Gategory=#Gategory AND Author=#Author AND Cost=#Cost AND [Date]=#Date ";
cmd.Parameters.AddWithValue("#ISBN", ISBNTB.Text);
cmd.Parameters.AddWithValue("#Name", NameTB.Text);
cmd.Parameters.AddWithValue("#Gategory", GategoryTB.Text);
cmd.Parameters.AddWithValue("#Author", AuthorTB.Text);
cmd.Parameters.AddWithValue("#Cost", CostTB.Text);
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Book removed to be sold!");
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Errow with the record which i try to delete
database records
You are facing this error because one/many parameters that you are passing to your query are of not the same type as it is in the database. Cross check them. and ideally should pass parameters to your query like this
cmd.Parameters.Add("#Date", OleDbType.Date); //note i have specified the db type
cmd.Parameters["#Date"].Value =dateTimePicker1.Value;
this will ensure that you have same types as defined in your database
Try:
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Value);
DateTimePicker.Text returns string representation of selected value, not the value itself.
How about?
cmd.Parameters.AddWithValue("#Date", dateTimePicker1.Value.ToString("dd-MM-yyyy"));
Hello I have a Stored Proc for the Registration Page, but I need ADO.NET to take values from various textboxes.
However, I'm recieving error like this:
"System.ArgumentException: No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type. "
public void InsertInfo()
{
String empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(empdb);
SqlCommand cmd = new SqlCommand("bridge_Type", conn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("#Name", TextBox2.Text));
cmd.Parameters.Add(new SqlParameter("#Mob2", TextBox3.Text));
cmd.Parameters.Add(new SqlParameter("#Email", TextBox14.Text));
cmd.Parameters.Add(new SqlParameter("#Emptype", dropdown1.SelectedValue));
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertInfo();
}
Then I used this format to add values from controls:
cmd.Parameters.Add(new SqlParameter("#EmpID", SqlDbType.Int));
cmd.Parameters("#EmpID").Value = TextBox1.Text;
I'm getting errors on:
Its showing errors for these kind of codes by appearing red line under 'Parameters'.
Non-invocable member 'System.Data.SqlClient.SqlCommand.Parameters' cannot be used like a method.
Try TextBox1.Text, TextBox is the Control. The Text property holds the String value.
cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
Try this code.
try
{
string empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
using (var conn = new SqlConnection(connString))
{
using (var cmd = new SqlCommand("bridge_Type",conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#EmpID",TextBox1.Text);
cmd.Parameters.AddWithValue("#Name", TextBox2.Text);
cmd.Parameters.AddWithValue("#Mob2", TextBox3.Text);
cmd.Parameters.AddWithValue("#Email", TextBox14.Text);
cmd.Parameters.AddWithValue("#EmpType",dropdown1.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
string msg = "Insert Error:"+ ex.Message;
throw new Exception(msg);
}
Make sure you are converting to the types same as the Parameter types in your stored proc ( Ex: If the parameter type of EmpID is int, you may need to convert the TextBox1.Text value to int. Check for null values also.
why dont u use this format?
cmd.Parameters.Add("#parameter", SqlDBType , size).value = TextBox1.Text