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;
}
Related
I have developed a winforms application with an SQL database in C#. Once I enter the data into the forms and press the display button it is displayed on the datagridview, but once I restart the application the data does not show up on the grid.
This is the code to add new data.
if (textBox1.Text != "" && textBox2.Text != "" && textBox3.Text != "")
{
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\shenal.mdf;Integrated Security=True";
cmd = new SqlCommand("insert into [dbo].[user] (Id,username,password) values(#id,#name,#state)", con);
// cmd.CommandText = "insert into [dbo].[user] (Id,username,password) values(#id,#name,#state)";
cmd.Parameters.AddWithValue("#id", textBox1.Text);
cmd.Parameters.AddWithValue("#name", textBox2.Text);
cmd.Parameters.AddWithValue("#state", textBox3.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
}
else {
MessageBox.Show("Please Provide Details!");
}
And this is the code to retrieve it.
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\shenal.mdf;Integrated Security=True";
con.Open();
DataTable dt = new DataTable();
adapt = new SqlDataAdapter("select * from [dbo].[user]", con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
I want to know how I could browse picture on desktop and upload the pic to my form and then save it to my database. This is what my friend did but it doesn't work for me. I don't know why please help.
MemoryStream ms = new MemoryStream();
pictureBox11.Image.Save(ms,System.Drawing.Imaging.ImageFormat.Jpeg);
SqlConnection con = new SqlConnection("Data Source=LAPTOP;Initial Catalog=db;Integrated Security=True");
SqlCommand cmd = new SqlCommand(query, con);
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"INSERT INTO tblperson([product name],[pics],[user]) VALUES(#value1,#value2,#value3)";
cmd.Parameters.AddWithValue("#value1", txtproductname.Text);
cmd.Parameters.AddWithValue("#value2", picbase64);
cmd.Parameters.AddWithValue("#value3", lbluser.Text);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Picture Saved");
con.Close();
txtproductname.Text = "";
pictureBox11.Image = LessonMidterm1.Properties.Resources.Person;
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");
}
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();
}
I have a table name is 'User_tbl' where i am saving data of all registered users and the same table is being used to verify the users during Login.
I want to update only 'LastSeen' column with current datetime after login.
Look at this picture.
code behind
protected void Submit(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from User_tbl where UserName =#username and Password=#password", con);
cmd.Parameters.AddWithValue("#username", txtUserName.Text);
cmd.Parameters.AddWithValue("#password", txtPWD.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
//to define the user seesion (starting user session)
Session["username"] = txtUserName.Text;
Response.Redirect("default2.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "LoginValidate", "<script language='javascript'> document.getElementById('errorMessage').innerHTML = 'Invalid Username or Password'</script>");
}
}
Do you mean something like this?
SqlConnection sqlConn = new SqlConnection(connection string here);
SqlCommand sqlComm = new SqlCommand();
sqlComm = sqlConn.CreateCommand();
sqlComm.CommandText = #"UPDATE User_tbl SET LastSeen=GetDate() WHERE UserName='#userName'";
sqlComm.Parameters.Add("#userName", SqlDbType.VarChar);
sqlComm.Parameters["#userName"].Value = txtUserName.Text;
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
You'd need to place something along those lines in your 'if (dt.Rows.Count > 0)' code.
You may wish to reuse the same connection that you created for your SELECT statement.
Many other options are available. Often this sort of thing is best achieved using a stored procedure, where you can check the login credentials and perform any related updates in a single request to the database server.