SqlDataAdapter Insert Database not working C# winform - c#

I am trying to insert data into a SQL Server database and show on DatagridView from a C# Winforms.
I click on the Insert button no error shows, but no data is being Insert into the database and Datagridview becomes blank.
I re-debug that can see data update in datagridview, but the database is not on Visual Studio Server Explorer DataBase(picture1).
On the other hand.I set breakpoint when click Insert Button,that jump over line 42~46.Directly to line 50.ex(picture2).
picture1
picture2
Edit:
The question now is when I click insert button,datagridview have update new data.But database no insert new data.Database only two data.
Edit2
I changed connection string AttachDbFilename.
AttachDbFilename=C:\Vis\NO4\WindowsFormsApplication1\App_Dat‌​a\Database1.mdf;
The value can insert database.
Here is the connection string:
<add name="con1" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True"
providerName="System.Data.SqlClient" />
Here is the Form_load and load_grid function
SqlConnection con;
SqlDataAdapter da;
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
string connectionString = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;
con = new SqlConnection(connectionString);
}
private void Form1_Load(object sender, EventArgs e)
{
load_grid();
}
public void load_grid()
{
dt.Clear();
SqlDataAdapter da1 = new SqlDataAdapter();
try
{
string sql = "SELECT * FROM profile";
con.Open();
da1.SelectCommand = new SqlCommand(sql, con);
da1.Fill(ds);
da1.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is the Insert Button
private void button1_Click(object sender, EventArgs e)
{
string ac = textBox1.Text;
string bd = textBox2.Text;
string sex = textBox2.Text;
string sql = "INSERT INTO profile(ac,bd,sex)VALUES('" + ac + "','" + bd + "','" + sex + "')";
try
{
con.Open();
da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(sql, con);
da.InsertCommand.ExecuteNonQuery();
da.Update(dt);
MessageBox.Show("INsert success...!!");
load_grid();
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here is the design of the Costumer table
CREATE TABLE [dbo].[profile] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[ac] NVARCHAR (50) NULL,
[bd] NVARCHAR (50) NULL,
[sex] NVARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC));
Not sure where the issue is here.

Picture2 shows an exception that connection is already open so, try following before opening a connection. You are calling load_grid(); before closing connection.
I have update all code, use it as explained below:
Edit- Second Revision:
public void load_grid()
{
dt.Clear();
SqlDataAdapter da1 = new SqlDataAdapter();
try
{
string sql = "SELECT * FROM profile";
con.Open();
da1.SelectCommand = new SqlCommand(sql, con);
da1.Fill(ds);
da1.Fill(dt);
con.Close();
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State != System.Data.ConnectionState.Closed)
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
string ac = textBox1.Text;
string bd = textBox2.Text;
string sex = textBox2.Text;
string sql = "INSERT INTO profile(ac,bd,sex)VALUES('" + ac + "','" + bd + "','" + sex + "')";
try
{
con.Open();
da = new SqlDataAdapter();
da.InsertCommand = new SqlCommand(sql, con);
da.InsertCommand.ExecuteNonQuery();
da.Update(dt);
con.Close();
MessageBox.Show("INsert success...!!");
load_grid();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State != System.Data.ConnectionState.Closed)
con.Close();
}
}

Related

refresh datagridview after insert or update or delete without selecting new sql query

I just want to clarify, can i refresh datagridview after insert or update or delete without selecting new sql query again ?
i have googled it, and still have no idea to do it.
here's my code
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
DataTable dtclubroom = new DataTable();
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
employee() //<- refresh datagridview
}
Button 4 is to load data, and button 5 inserting data also load data. is there a way refresh datagridview without calling employee() method again ?
You can do it in couple of ways.
Add the newly inserted record to your datatable (you need to use a global datatable variable for this) and refresh your Grid View using this datatable.
You can add the newly inserted record directly to the Grid View
You can follow these techniques also for DELETE and UPDATE
Here is the implementation of idea #1 for your existing code :
DataTable dtclubroom = new DataTable();
private void button4_Click(object sender, EventArgs e)
{
employee();
}
public void employee()
{
SqlCommand command = new SqlCommand();
SqlDataAdapter adapter = new SqlDataAdapter(command.CommandText, myConnection);
try
{
myConnection.Open();
dtclubroom.Clear();
command.Connection = myConnection;
command.CommandText = "Select * from employee ";
adapter.SelectCommand = command;
adapter.Fill(dtclubroom);
dataGridView2.DataSource = dtclubroom;
}
catch (Exception ex)
{
MessageBox.Show("error" + ex);
}
finally
{
myConnection.Close();
}
}
private void button5_Click(object sender, EventArgs e)
{
SqlCommand command2 = new SqlCommand();
try
{
myConnection.Open();
command2.CommandText = "insert into employee (name,id) values (#name,#id)";
command2.Connection = myConnection;
command2.Parameters.AddWithValue("#name","Leon");
command2.Parameters.AddWithValue("#id", "002");
command2.ExecuteNonQuery();
DataRow dr = dtclubroom.NewRow();
dr["name"] = "Leon";
dr["id"] = "002";
dtclubroom.Rows.Add(dr);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
finally
{
myConnection.Close();
}
dataGridView2.DataSource = dtclubroom; //<- refresh datagridview
}
Look that the datatable declaration is moved up and you need to place it in top of your class :
DataTable dtclubroom = new DataTable();
Nothing else need to be global.

How to update data from DataGridView to database? ERROR - Cannot insert value NULL

I'm trying to update data from DataGridView to my database. While I was looking for the solution of this problem on google, I noticed that all of the solutions are managed by using class variables (for DataTable,SqlDataAdapter,...). I'm trying to do this just by using function variables.
This is how I loaded data to DataGridView:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID = #ID",connection);
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
DataTable dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
DataGridView.DataSource = dataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING TO DATABASE!");
}
}
DataGridView is showing just those sentences that match particular ID.
This is what I have tried so far:
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand("SELECT SENTENCE FROM Sentences WHERE CategoryID IN(#CategoryID)", connection);
cmd.Parameters.Add("#CategoryID",SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
This is the error that comes up:
Cannot insert value NULL into column CategoryID, table ...;column does not allow nulls.Insert fails. The statement has been terminated.
if your Id data type is int ,you don't need put it inside "".
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
string connString;//WHAT EVER IT IS
string Query=string.Format(#"SELECT QUESTION FROM Questions WHERE CategoryID = '{0}'",CategoryID);
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(Query, connection);
connection.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd,connString);
DataTable DataTable=new DataTable();
dataAdapter.Fill(DataTable);
datagridview1.DataSource=DataTable;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
catch (SqlException)
{
MessageBox.Show("SqL Error!");
}
}
SOLUTION of my problem:
Firstly, I have shown all columns of database table in DataGridView and then I have hided Primary Key column and CategoryID column. That is shown in the following code:
private void LoadDataGridView(int ID)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Sentences WHERE CategoryID = #ID";
cmd.Connection = connection;
cmd.Parameters.Add("#ID",SqlDbType.Int).Value = ID;
dataTable = new DataTable();
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
dataAdapter.Fill(dataTable);
dataGridView.DataSource = dataTable;
dataGridView.Columns[0].Visible = false;
dataGridView.Columns[2].Visible = false;
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE!");
}
}
Then, I have set default value only for CategoryID column, because Primary Key column has an option of Auto - Increment. That is show in the following code:
private void dataGridView_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e)
{
e.Row.Cells["CategoryID"].Value = CategoryID;
}
The last thing I have done is implement the code for RefreshBtn (the following code is practically the same as the code in question):
private void RefreshBtn_Click(object sender, EventArgs e)
{
try
{
SqlConnection connection = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Questions WHERE CategoryID = #CategoryID";
cmd.Connection = connection;
cmd.Parameters.Add("#CategoryID", SqlDbType.Int).Value = CategoryID;
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.Update(dataTable);
}
catch (Exception)
{
MessageBox.Show("ERROR WHILE CONNECTING WITH DATABASE !");
}
}

Can you help me to show datagridview and Refresh after update?

This is my code and error message when you running say:
An unhandled exception of type System.Data.SqlClient.SqlException
occurred in System.Data.dll
on this da.fill(dt);
SqlConnection con = new SqlConnection("Data Source=ANTONIANGGA-PC\\SQLEXPRESS;Initial Catalog=FullandStarving;Integrated Security=True");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
public FormProduksi()
{
InitializeComponent();
showgridview();
}
private void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure; done :D
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
showgridview();
clear();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
that update successfully but cant refresh, so i do quit that form and open can see it
You are closing the connection
con.Close();
and then using
da.Fill(dt);
Just swap this lines:
showgridview();
con.Close();
For example with DbDataAdapter.Fill:
Notes:
1
Yoy should use parametrized queries so you avoid SQL Injection attacks:
var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con);
cmd.Parameters.AddWithValue("#id", id.Text);
2
Wrap SqlConnection and SqlCommand into using so any resources used by those would disposed:
string position;
using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
con.Open();
using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = #id", con))
{
cmd.Parameters.AddWithValue("#id", id.Text);
var name = cmd.ExecuteScalar();
if (name != null)
{
position = name.ToString();
Response.Write("User Registration successful");
}
else
{
Console.WriteLine("No Employee found.");
}
}
}
Credit
Just change the showgridview() function as below where connection is opened & closed properly.
Also check your sql query ,provide space and maintain syntax of query :
SELECT * FROM Produksi
Error screenshot clearly depicts that stored procedure with such name don't exist
comment out those lines as code below :
void showgridview()
{
con.Open();
dt.Clear();
cmd = new SqlCommand("SELECT * FROM Produksi", con);
//cmd.CommandType = CommandType.StoredProcedure;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
Then you wont be having connection issues and errors related .
Button Click code change the closing connection as below:
private void button2_Click(object sender, EventArgs e)
{
//Datetimepicker to Database
string dProduksi = DateTime.Parse(dtmProduksi.Text).ToString("yyyy-MM-dd");
try
{
con.Open();
cmd = new SqlCommand("insert into Produksi (IDProduksi,IDPhoto,TanggalProduksi,NamaKaryawan,KeteranganPhoto) Values('" + txtIdpro.Text + "','" + txtIdPhoto.Text + "','" + dProduksi + "','" + txtNamaKaryawan.Text + "','" + rxtKtrphoto.Text + "')", con);
cmd.ExecuteNonQuery();
MessageBox.Show("Update telah di jalankan");
con.Close();
showgridview();
clear();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Also, for further reading:
parameterized queries vs. SQL injection
Why do we always prefer using parameters in SQL statements?

Windows Form Application update query not save data

I try to use an update query in my C# windows form application. I do not get any errors, it just seems not to save the data I try to update. Take a look at the code:
private void button2_Click(object sender, EventArgs e)
{
try
{
string myConnection = connection;
MySqlConnection myConn = new MySqlConnection(myConnection);
myConn.Open();
MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
myDataAdapter.UpdateCommand = new MySqlCommand(" update users set username=" + textBox1.Text + " where username=" + username + " ", myConn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(myDataAdapter);
DataSet ds = new DataSet();
myConn.Close();
MessageBox.Show("Changes has been saved.");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The username is an string passed from another form (gridview) ..
I found an solution for this on the internet. What I cam up with is:
private void button2_Click(object sender, EventArgs e)
{
string myConnection = connection;
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand cmdDataBase = new MySqlCommand("UPDATE `users` SET username='Test' WHERE username='CurrentName' ", myConn);
MySqlDataReader myReader;
try
{
myConn.Open();
myReader = cmdDataBase.ExecuteReader();
myConn.Close();
MessageBox.Show("Changes has been saved!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Adding data in sql Table columns

I have this basic WinForms application user interface:
And I want to add the data both to the DataGridView and the sql table, when the "Gem" button is clicked. I have this following code:
private void Form2_Load(object sender, EventArgs e)
{
try
{
con = new SqlConnection();
con.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Produkt.mdf;Integrated Security=True";
con.Open();
//adap = new SqlDataAdapter("select SN, FName as 'Navn', MName as 'Vare nr', LName as 'Antal', Age from Produkt", con);
string sql = "SELECT Navn, Varenr, Antal, Enhed, Priseksklmoms, Konto FROM ProduktTable";
adap = new SqlDataAdapter(sql, con);
ds = new System.Data.DataSet();
adap.Fill(ds, "ProduktTable");
dataGridView1.DataSource = ds.Tables["ProduktTable"];
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void button1_Click(object sender, EventArgs e)
{
string navn = textBox2.Text;
int varenr = int.Parse(textBox3.Text);
float antal = (float)Convert.ToDouble(textBox4.Text);
string enhed = textBox5.Text;
string konto = comboBox2.Text;
float pris = (float)Convert.ToDouble(textBox6.Text);
dataGridView1.Rows[0].Cells[0].Value = navn;
dataGridView1.Rows[0].Cells[1].Value = varenr;
string StrQuery;
try
{
SqlCommand comm = new SqlCommand();
comm.Connection = con;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
StrQuery = #"INSERT INTO tableName ProduktTable ("
+ dataGridView1.Rows[i].Cells["Varenr"].Value + ", "
+ dataGridView1.Rows[i].Cells["Antal"].Value + ");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show("Error\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
This is just an example with the purpose for storing the string "navn" and the integer "Varenr" in the DataGridView and the sql. When Im running the application and clicking on the button, following error occurs:
What's wrong with the procedure ?.
Thanks in advance
The format for an insert name doesn't require the words tableName. It wants the actual table name.
INSERT INTO tableName ProduktTable
should be
INSERT INTO ProduktTable
assuming Produ**K**tTable isn't a typo.

Categories