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_Data\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();
}
}
i have this source , i want create a search button to find the id & name & date & very important ( retrieve the image)
&
another search button to find the name recorded between to date
such as 21/2/2012 & 1/3/2012
find all record between to date .
namespace _2015
{
public partial class import : Form
{
public import()
{
InitializeComponent();
}
private void bt_save_Click(object sender, EventArgs e)
{
byte[] imagebt = null;
FileStream fstream = new FileStream(this.txt_ipath.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imagebt = br.ReadBytes((int)fstream.Length);
string constring = "Data Source=SKYNET-PC;Initial Catalog=2015;Integrated Security=True";
string Query = "insert into t_import (id,name,barwar,imgc)" + "values('" + this.t_id.Text + "','" + this.t_name.Text + "','"+this.dt1.Text+"',#IMG); ";
SqlConnection condatabase = new SqlConnection(constring);
SqlCommand cmddatabase = new SqlCommand(Query, condatabase);
SqlDataReader myreader;
try
{
condatabase.Open();
{
cmddatabase.Parameters.Add(new SqlParameter("#IMG",imagebt));
myreader = cmddatabase.ExecuteReader();
MessageBox.Show("پاشەکەوت کرا");
while (myreader.Read())
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void update_Click(object sender, EventArgs e)
{
string constring = "Data Source=SKYNET-PC;Initial Catalog=2015;Integrated Security=True";
string Query = "update t_import set id='" + this.t_id.Text + "',name='" + this.t_name.Text + "' where id='"+this.t_id.Text+"' ; ";
SqlConnection condatabase = new SqlConnection(constring);
SqlCommand cmddatabase = new SqlCommand(Query, condatabase);
SqlDataReader myreader;
try
{
condatabase.Open();
{
myreader = cmddatabase.ExecuteReader();
MessageBox.Show("بە سەرکەوتوویی نوێ کرایەوە");
while (myreader.Read())
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void bt_delete_Click(object sender, EventArgs e)
{
string constring = "Data Source=SKYNET-PC;Initial Catalog=2015;Integrated Security=True";
string Query = "delete from t_import where id='" + this.t_id.Text + "' ; ";
SqlConnection condatabase = new SqlConnection(constring);
SqlCommand cmddatabase = new SqlCommand(Query, condatabase);
SqlDataReader myreader;
try
{
condatabase.Open();
{
myreader = cmddatabase.ExecuteReader();
MessageBox.Show("بە سەرکەوتوویی سردرایەوە");
while (myreader.Read())
{
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void browse_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files(*.jpg)|*.jpg|PNG Files(*.PNG)|*.png|All Files (*.*)|(*.*)";
if (dlg.ShowDialog() == DialogResult.OK)
{
string picpath = dlg.FileName.ToString();
txt_ipath.Text = picpath;
pictureBox1.ImageLocation = picpath;
}
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void dt1_ValueChanged(object sender, EventArgs e)
{
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
}
}
}
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}
I need to populate a combobox in page1 with the address details of a selected name contained in another combobox held in the MainWindow page. I have tried the code below, but combobox name in MainWindow is not recognised.
MainWindow:
private void displayParts()
{
try
{
sc.Open();
string Query = "select * from Parts";
SqlCommand createCommand = new SqlCommand(Query, sc);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
string Name = dr.GetString(1);
cbParts.Items.Add(Name);//Displaying a list in the Combo Box
}
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Page1:
private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
string constring = "Data Source=.;Initial Catalog=**.MDF;Integrated Security=True";
DataContext=MainWindow.
string Query = "select * from Partners where Name='" + cbParts.SelectedItem.ToString() + "' ;";
SqlConnection conDataBase = new SqlConnection(constring);
SqlCommand cmdDataBase = new SqlCommand(Query, conDataBase);
SqlDataReader myReader;
try
{
sc.Open();
myReader = cmdDataBase.ExecuteReader();
if (myReader.Read())
{
txtPartner.Text = myReader["Name"].ToString();
}
myReader.Close();
sc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
// may need to cast this to your MainWindow's type
var mainWindow = Application.Current.MainWindow;
//...
mainWindow.cbParts.Items.Add(Name);
Additionally, you could bind your combobox to an ObservableCollection property, and add the items to the collection.