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();
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;
}
I want to show data from my database in dataGridView after saved new record. After I clicked button, the data saved, but not show in datagridview. How can I show that data?
private void btn_add_Click(object sender, EventArgs e)
{
{
if (textBox_tarikh.Text == "" || textBox_resit.Text == "" || textBox_bayaran.Text == "")
{
MessageBox.Show("Please Fill In The Blank");
}
else
{
String bResult = textBox_ic.Text;
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30"; // add your conncetion string here
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("INSERT Pembayaran (Description, Date, No_Resit, Payment, Studentic) VALUES (#Description, #date, #resit, #payment, #val)", connection);
cmd.Parameters.AddWithValue("#val", bResult);
cmd.Parameters.AddWithValue("#Description", label4.Text);
cmd.Parameters.AddWithValue("#date", Convert.ToDateTime(textBox_tarikh.Text));
cmd.Parameters.AddWithValue("#resit", textBox_resit.Text);
cmd.Parameters.AddWithValue("#payment", textBox_bayaran.Text);
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "pembayaran_table");
connection.Close();
dataGridView3.DataSource = ds;
dataGridView3.DataMember = "pembayaran_table";
cmd.Connection.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved Successfully");
}
catch (Exception ex)
{
//throw new Exception("Error " + ex.Message);
MessageBox.Show("Receipt No. is already use");
}
}
You can try :
private void btn_add_Click(object sender, EventArgs e)
{
string bResult = textBox_ic.Text;
if (textBox_tarikh.Text == "" || textBox_resit.Text == ""||textBox_bayaran.Text == "")
{
MessageBox.Show("Please Fill In The Blank");
}
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\acap\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand cmd ;
try
{
if(connection.State == ConnectionState.Closed) connection.Open();
cmd = new SqlCommand("INSERT Pembayaran (Description, Date, No_Resit, Payment, Studentic) VALUES (#Description, #date, #resit, #payment, #val)", connection);
cmd.Parameters.AddWithValue("#val", bResult);
cmd.Parameters.AddWithValue("#Description", label4.Text);
cmd.Parameters.AddWithValue("#date", Convert.ToDateTime(textBox_tarikh.Text));
cmd.Parameters.AddWithValue("#resit", textBox_resit.Text);
cmd.Parameters.AddWithValue("#payment", textBox_bayaran.Text);
cmd.Executenonquery();
SqlDataAdapter da = new SqlDataAdapter("Select * from Pembayaran",connection);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView3.DataSource = dt;
}
catch(Exception ex)
{
}
finally
{
if(connection.State == ConnectionState.Open) connection.Close();
}
}
You just need to update your DataGridView's Datasource after inserting record to DB.
Firstly, I don't see any data binding code in your snippet such as DataGridView.DataSource = " ", DataGridView.DataBind();
What you can try to do it after inserting data, make use of ##IDENTITY to retrieve the id of what you have inserted. Then make use of the id retrieved to capture the new record.
##IDENTITY
I have noticed in your code snippet, you used the same query.
SqlDataAdapter dataadapter = new SqlDataAdapter(cmd);
You should write another SqlStatement and call it from SqlDataAdapter
For example:
// Assumes that connection is a valid SqlConnection object.
string queryString =
"SELECT CustomerID, CompanyName FROM dbo.Customers";
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
DataSet customers = new DataSet();
adapter.Fill(customers, "Customers");
Populating a DataSet from a DataAdapter
I am creating one application my requirement is what when column name Status is N in Registration table, then current form should hide and Login form should be open.
If Status is not N then its should be open Registration_Form. I'm trying but it's causing
Error creating window handle
on the rf.Show() call.
on insert button code
string status = "Y";
//Random random = new Random();
//int randomNumber = random.Next(0, 100);
string random1 = System.Web.Security.Membership.GeneratePassword(10, 0);
string concate = textBox1.Text + "-" + textBox2.Text + "-" + textBox3.Text.Substring(textBox3.Text.Length - 4) + "-" + random1;
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string SqlString = "Insert Into Registration (Name,Last_Name,Contact_No,Address,Insert_Date,Registration_key,Status) Values (?,?,?,?,?,?,?)";
//using (OleDbCommand cmd = new OleDbCommand(SqlString, con))
//{
OleDbCommand cmd = new OleDbCommand(SqlString, con);
con.Open();
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Last_Name", textBox2.Text);
cmd.Parameters.AddWithValue("#Contact_No", textBox3.Text);
cmd.Parameters.AddWithValue("#Address", textBox4.Text);
cmd.Parameters.AddWithValue("#Insert_Date", textBox5.Text);
cmd.Parameters.AddWithValue("#Registration_key", concate);
cmd.Parameters.AddWithValue("#Status", status);
//}
int n = cmd.ExecuteNonQuery();
con.Close();
if (n > 0)
{
MessageBox.Show("Data Inserted Successfully,NOW PLEASE ACTIVATE APPLICATION PUTTING ACTIVATE KEY ", "Data Inserted ", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
on update button code --
string Status = "N";
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string recover = "SELECT Registration_key from Registration where Registration_key='" + textBox6.Text + "'";
OleDbCommand cmd = new OleDbCommand(recover, con);
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
textBox6.Text = reader["Registration_key"].ToString();
if (con.State == ConnectionState.Open)
{
con.Close();
}
string cmd1 = "update Registration set Status=#Status where Registration_key=#Registration_key";
cmd = new OleDbCommand(cmd1, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Status", Status);
cmd.Parameters.AddWithValue("#Registration_key", textBox6.Text);
con.Open();
int n2 = cmd.ExecuteNonQuery();
con.Close();
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Invalid Activated Key", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
con.Close();
on load event--
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
i got a solution i remove e
lse if (compare != Comparing)
{
Registration_Form rf = new Registration_Form();
rf.Show();
}
this and instead that normal use else condition
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
con.ConnectionString = connectionString;
string Comparing="N";
string query = "select Status from Registration where Status='N'";
con.Open();
OleDbCommand cmd = new OleDbCommand(query, con);
string compare = Convert.ToString(cmd.ExecuteScalar());
con.Close();
if (compare == Comparing)
{
this.Hide();
Login_Page lp = new Login_Page();
lp.Show();
}
else
{
MessageBox.Show("Pls Register yourself");
}
this code giving me what requirement i want
I have table consisting columns(....,....,....,BLOCK) in my database.
The BLOCK column has bit datatype(True,False).
When BLOCK column has False, the data should be fetched from the database.
When BLOCK column has True, the data should not be fetched resulting in throwing an error.
When I give the name of a particular person in textbox and click button, the above operation must be performed
my button click c# coding is...
protected void ImageButton5_Click(object sender, ImageClickEventArgs e)
{
string selectsql = "SELECT * FROM UserDetailsTwo";
using (SqlConnection con = new SqlConnection(#"Data Source=ENTERKEY001;Initial Catalog=ContactManagement;Integrated Security=True"))//DataBase Connection
{
SqlCommand selectCommand = new SqlCommand(selectsql, con);
con.Open();
SqlDataReader SelectReader = selectCommand.ExecuteReader();
while (SelectReader.Read())
{
Boolean BLOCK = Convert.ToBoolean(SelectReader["BLOCK"]);
if (BLOCK == false)
{
//con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SearchUser";
cmd.Parameters.AddWithValue("#NAME", TextBox4.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
else
{
Response.Write("Error");
}
}
SelectReader.Close();
}
}
You are trying to use an SQLDataReader like a DataAdapter.
SelectReader = selectCommand.ExecuteReader();
while (SelectReader.Read())
{
Int64 BLOCK = Convert.ToInt64(SelectReader["BLOCK"]);
if (BLOCK == false)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SearchUser";
cmd.Parameters.AddWithValue("#NAME", TextBox4.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataBind();
con.Close();
}
else
{
Response.Write("Error");
}
}
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader%28v=vs.110%29.aspx
I want to create a simple form where I want to validate to show message if same users exists.
The function usernamecheck() checks for validation and displays error if same user exists but when I click submit button it still submits same user.
private void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
cmd.Parameters.AddWithValue("#bdate", textBox7.Text.ToString());
UserNameCheck();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
public void UserNameCheck()
{
string constring = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from cntc_employee where emp_alias= #alias", con);
cmd.Parameters.AddWithValue("#alias", this.textBox3.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Alias "+ dr[1].ToString() +" Already exist");
break;
}
}
}
Problem : You are Inserting the record always without check wether user exist or not.
Solution :
You need to return the boolean value from the UserNameCheck() function.
retrun true if username exist.
return false if username doesnot exist.
then execute the Insert Query if and only if UserNameCheck function returns false
Try This:
Chnage the UserNameCheck() function code as below to return the boolean value.
public bool UserNameCheck()
{
string constring = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select count(*) from cntc_employee where emp_alias= #alias", con);
cmd.Parameters.AddWithValue("#alias", this.textBox3.Text);
con.Open();
int TotalRows = 0;
TotalRows = Convert.ToInt32(cmd.ExecuteScalar());
if(TotalRows > 0)
{
MessageBox.Show("Alias "+ dr[1].ToString() +" Already exist");
return true;
}
else
{
return false;
}
}
Now Change the Submit function code to verify the UserNameCheck() return value, proceed to the insertion only if the UserNameCheck() function returns false(when user does not exist)
private void submit_Click(object sender, EventArgs e)
{
if(!UserNameCheck())
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(#fname,#lname,#alias,#contact,#address,#company,#bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("#fname", textBox1.Text);
cmd.Parameters.AddWithValue("#lname", textBox2.Text);
cmd.Parameters.AddWithValue("#alias", textBox3.Text);
cmd.Parameters.AddWithValue("#contact", textBox4.Text);
cmd.Parameters.AddWithValue("#address", textBox5.Text);
cmd.Parameters.AddWithValue("#company", textBox6.Text);
cmd.Parameters.AddWithValue("#bdate", textBox7.Text.ToString());
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
}
First fire a select query that checks whether a user exists or not. If not then fire insert statement.
you should make a select count by name for the user first, and if the counter is bigger than 0 make the insert