I have binded 3 comboboxes separately to 3 different tables. Whenever i select value for metroComboBox2, it gives me this error "Column 'Cor_ID' is constrained to be unique. Value '103' is already present." I don't why this error is coming. What is the cause for this error?
con = new SqlConnection(constr);
con.Open();
DataTable dt = new DataTable();
String query = "Insert into Teacher (ID,Name,FName,Age,Qualification,Dep_ID,Cor_ID,Sem_ID,Password) VALUES(#ID,#Name,#FName,#Age,#Qualification,#Dep_ID,#Cor_ID,#Sem_ID,#Password)";
cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#ID", metroTextBox1.Text);
cmd.Parameters.AddWithValue("#Name", metroTextBox2.Text);
cmd.Parameters.AddWithValue("#FName", metroTextBox3.Text);
cmd.Parameters.AddWithValue("#Age", metroTextBox4.Text);
cmd.Parameters.AddWithValue("#Qualification", metroTextBox5.Text);
cmd.Parameters.AddWithValue("#Dep_ID", metroComboBox1.GetItemText(metroComboBox1.SelectedItem));
cmd.Parameters.AddWithValue("#Cor_ID", metroComboBox2.GetItemText(metroComboBox2.SelectedItem));
cmd.Parameters.AddWithValue("#Sem_ID", metroComboBox3.GetItemText(metroComboBox3.SelectedItem));
cmd.Parameters.AddWithValue("#Password", metroTextBox7.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted");
}
Related
I'm trying to save data from textboxes to a database, the new data appears in the grid, but it doesn't appear in the database table. When I close the application and restart it, the data which appeared in the grid disappears. There is no error, but no data is uploaded. It works if I hardcode the path but I wanted to use the DataDirectory so that it can be used on other computers. The database is set to Copy if newer (for the copy to output directory). Could someone help?
if (dialogResult == DialogResult.Yes)
{
SqlCommand cmd;
SqlConnection con;
con = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = |DataDirectory|\TestDatabase.mdf;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT INTO Patient (FirstName, LastName, DOB) VALUES (#FirstName,#LastName,#DOB)", con);
cmd.Parameters.AddWithValue("#FirstName", txtFirstName.Text);
cmd.Parameters.AddWithValue("#LastName", txtLastName.Text);
cmd.Parameters.AddWithValue("#DOB", dateTimePicker1.Text);
cmd.ExecuteNonQuery();
con.Close();
SqlDataAdapter SqlDA = new SqlDataAdapter("SELECT * FROM Patient", con);
DataTable dtbl = new DataTable();
SqlDA.Fill(dtbl);
dataGridView1.DataSource = dtbl;
}
When I press the register button, a MessageBox will show up and then this happens:
No mapping exists from object type System.Windows.Forms.DateTimePicker to a known managed provider native type.
How do I fix this?
SqlConnection sqlcon = new SqlConnection();
sqlcon.ConnectionString = #"Data Source=MYCOMPUTER-PC\SQLEXPRESS;Database=COMPPROG;User
Id=user;Password=password";
SqlCommand scmd = new SqlCommand("SELECT COUNT (*) as cnt from USERACCOUNT", sqlcon);
SqlCommand cmd = sqlcon.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO USERACCOUNT
(FName,MName,Sname,TxtBirth,comboGender,textBox8,textBox1,textBox2)
VALUES(#FName,#MName,#Sname,#TxtBirth,#comboGender,#textBox8,#textBox1,#textBox2)";
cmd.Parameters.AddWithValue("#FName", FName.Text);
cmd.Parameters.AddWithValue("#MName", MName.Text);
cmd.Parameters.AddWithValue("#Sname", Sname.Text);
cmd.Parameters.AddWithValue("#TxtBirth", TxtBirth);
cmd.Parameters.AddWithValue("#textBox8", textBox8.Text);
cmd.Parameters.AddWithValue("#textBox1", textBox1.Text);
cmd.Parameters.AddWithValue("#textBox2", textBox2.Text);
cmd.Parameters.AddWithValue("#comboGender", comboGender);
sqlcon.Open();
MessageBox.Show("Record added sucessfully!", "Registration Success!");
cmd.ExecuteNonQuery();
sqlcon.Close();
Like #gunr2171 said in comments problem is from this line so change it like this :
cmd.Parameters.AddWithValue("#TxtBirth", TxtBirth.Value);
This is value of TxtBirth for your query.
Edit :
And your error means you are passing the DatePicker itself and it can not be done.
I have this code that is suppose to get me the last registered MemberId from column but I cant get it to work, what have I got wrong?
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT top 1 * FROM Medleminfo ORDER BY MemberId desc";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
last_id = Convert.ToInt32(dr["MemberId"].ToString());
}
return last_id;
Output last_id is supposed to be used in this method:
public DataTable display_tiger_info(int member_id)
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"SELECT Medleminfo.MemberId, Medleminfo.Förnamn, Medleminfo.Efternamn,
Medleminfo.Adress, Medleminfo.Telefon, Tigerinfo.Tigernamn,Tigerinfo.Födelsedatum
FROM Medleminfo, Tigerinfo WHERE Medleminfo.MemberId = Tigerinfo.OwnerID ";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt;
}
Why not just use the 'Max' function? This is assuming that your looking for the largest number in the sequence. The way your question is worded though would suggest that you should have a date column to search by instead. Also if you want just one result then try execute scalar instead of putting it into a data table and going through all that extra work.
int id = 0;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using(var command = new SqlCommand("Select Max(MemberId) from Medleminfo", connection))
{
id = (int)command.ExecuteScalar();
}
}
I think your issues is probably cmd.ExecuteNonQuery() according to the msdn SqlCommand.ExecuteNonQuery Method Executes a Transact-SQL statement against the connection and returns the number of rows affected.
You will probably be wanting to use ExecuteReader in something like the following
if (con.State == ConnectionState.Open)
{
con.Close();
}
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
//All you want is the member Id why get all the columns
cmd.CommandText = "SELECT top 1 MemberId FROM Medleminfo ORDER BY MemberId desc";
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
last_id = Convert.ToInt32( reader[0]));
}
return last_id;
UPDATE: This code might solve your problem but I did not identify the issue correctly cmd.ExecuteNonQuery() should be removed it is not doing anything. adapter.Fill() should be executing the command and I do not know why you are not getting the expected response.
I'm trying to insert new values into my database using visual studio and here is my code:
SqlCommand cmd = new SqlCommand();
SqlConnection conn = new SqlConnection();
conn.ConnectionString = dbconnectionstring;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "INSERT INTO Data_ConfigInfo (TypeID, Name, ValidFromDate, ValidToDate, ValidFromSOP, ValidToSOP, Description)" +
"VALUES(#TypeID, #Name, #ValidFromDateTime, #ValidToDateTime, #ValidFromSOP, #ValidToSOP, #Description)";
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
if(Logg.ValidFrom.Equals(null)) {
cmd.Parameters.AddWithValue("#ValidFromDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidFromDateTime", Logg.ValidFrom);
}
if (Logg.ValidTo.Equals(null))
{
cmd.Parameters.AddWithValue("#ValidToDateTime", DBNull.Value);
}
else
{
cmd.Parameters.AddWithValue("#ValidToDateTime", Logg.ValidFrom);
}
cmd.Parameters.AddWithValue("#ValidFromSOP", Logg.ValidFromSOP);
cmd.Parameters.AddWithValue("#ValidToSOP", Logg.ValidToSOP);
cmd.Parameters.AddWithValue("#Description", Logg.Description);
cmd.ExecuteNonQuery();
conn.close();
conn.dispose();
But at the line
cmd.ExecuteNonQuery();
I get the error
invalid column name for ValidToDateTime and ValidFromDateTime.
Both are datetime variables. I can't seem to find the error. Any ideas?
This is how my datatable looks
Your DB table has columns ValidFromDateTime, ValidToDateTime, but your column list in the INSERT statement has ValidFromDate, ValidToDate. Are you sure that it is not a typo when posting here?
Did you forgot '#'?
cmd.Parameters.AddWithValue("TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("Name", Logg.Name);
cmd.Parameters.AddWithValue("#TypeID", Logg.TypeID);
cmd.Parameters.AddWithValue("#Name", Logg.Name);
I have a database that contains a Customer table with the following columns : CustID, CustName, ICNumber, ContactNumber and Address. It is a service-based database.
string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(localdb);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID,CustName,ICNumber,ContactNumber,Address)values(#CustID,#CustName,#ICNumber,#ContactNumber,#Address)", con);
cmd.Parameters.AddWithValue("#CustID", txtCustID.Text);
cmd.Parameters.AddWithValue("#CustName", txtCustName.Text);
cmd.Parameters.AddWithValue("#ICNumber", txtICNum.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
con.Close();
The code compiles and runs. The problem I am having is that the record is not added into the table after cmd.ExecuteNonQuery(); is called.
Why is the record not showing up in the database table?
You forgot to close the quotes " on the insert command. It is nice to use try/catch to avoid problems with your insert, for sample:
string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;
try
{
SqlConnection con = new SqlConnection(localdb))
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID, CustName, ICNumber, ContactNumber, Address) VALUES (#CustID, #CustName, #ICNumber, #ContactNumber, #Address)", con);
cmd.Parameters.AddWithValue("#CustID", txtCustID.Text);
cmd.Parameters.AddWithValue("#CustName", txtCustName.Text);
cmd.Parameters.AddWithValue("#ICNumber", txtICNum.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
cmd.Parameters.AddWithValue("#Address", txtAddress.Text);
cmd.ExecuteNonQuery();
}
catch
{
// some errors
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}