I'm new to C# so please check my code. It stops in cmd.ExecuteNonQuery(); here, but when I simply insert date it works but not inserting with combo box.
Is the SQL query right or not?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace newpro
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
object sel = comboBox1.SelectedValue;
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES ('"+txtfname.Text+"','"+txtfname.Text+"', '"+txtuname.Text+"', '"+txtpass.Text+"', '"+txtemail.Text+"','"+comboBox1+"');",con);
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record inserted");
con.Close();
}
}
}
you have to get the selected value from your Combobox. combobox1 retuns only the class name System.Windows.Forms.ComboBox
Besides others, it is recommended to use parameter .. like this:
private void button1_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=c:\users\abdul samad\documents\visual studio 2013\Projects\newpro\newpro\Database1.mdf;Integrated Security=True"))
{
try
{
using (var cmd = new SqlCommand("INSERT INTO registor (Name, FullName, Password, Email, Gander) VALUES (#Name,#Fullname,#Password,#Email, #Gander)"))
{
cmd.Connection = con;
cmd.Parameters.Add("#Name", txtfname.Text);
cmd.Parameters.Add("#Fullname", txtfname.Text);
cmd.Parameters.Add("#Password", txtpass.Text);
cmd.Parameters.Add("#Email", txtemail.Text);
cmd.Parameters.Add("#Gander", comboBox1.GetItemText(comboBox1.SelectedItem));
con.Open()
if(cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record inserted");
}
else
{
MessageBox.Show("Record failed");
}
}
}
catch (Exception e)
{
MessageBox.Show("Error during insert: " + e.Message);
}
}
}
public void insertfunction()
{
string sqlconn = ConfigurationManager.ConnectionStrings["myConnection"].ConnectionString;
SqlConnection cn = new SqlConnection(sqlconn);
cn.Open();
String query = "insert into PatientRecords values(#Patient_Name,#Cnic,#Phone,#Address,#Age,#Doctor_Reference,#City)";
SqlCommand cmd = new SqlCommand(query,cn);
// cmd.Parameters.AddWithValue("#Patient_Id", pid.Text);
cmd.Parameters.AddWithValue("#Patient_Name", pname.Text);
cmd.Parameters.AddWithValue("#Cnic", pcnic.Text);
cmd.Parameters.AddWithValue("#Phone", pphone.Text);
cmd.Parameters.AddWithValue("#Address", paddress.Text);
cmd.Parameters.AddWithValue("#City", cmbopcity.GetItemText(cmbopcity.SelectedItem));
cmd.Parameters.AddWithValue("#Age", page.Text);
cmd.Parameters.AddWithValue("#Doctor_Reference", prefdoc.Text);
if (cmd.ExecuteNonQuery() > 0)
{
MessageBox.Show("Record Successfully inserted");
}
else
{
MessageBox.Show("Record failed");
}
cn.Close();
}
Related
I am working on a SQL connection through C# but on the sqlCmd.ExecuteNonQuery(); line, when I run it and put information into the form it does not work. Crashing and giving me the error, the code for my program follows. Also include a screenshot of the form. I have been trying to fix this for a while but no luck, tried switching the code around and more but generally just didn't work.
https://i.stack.imgur.com/rpFGj.png
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormApp32
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";
private void Form2_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
if (textBox5.Text + textBox6.Text == " ")
MessageBox.Show("Please fill mandatory fields");
sqlCon.Open();
SqlCommand sqlCmd = new SqlCommand("UserAdd");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#First_Name", textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Last_Name", textBox2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Email_ID", textBox3.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Contact", textBox4.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Address", richTextBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Department", comboBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Username", textBox5.Text.Trim());
using (var connectionString = new SqlConnection("Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True"))
using (var cmd = new SqlDataAdapter())
using (var insertCommand = new SqlCommand("INSERT INTO Application VALUES (#First_Name, #Last_Name, #Email_ID, #Contact, #Address, #Gender, #Department, #Username, #Password) "))
{
insertCommand.Connection = connectionString;
cmd.InsertCommand = insertCommand;
connectionString.Open();
}
sqlCmd.ExecuteNonQuery();
MessageBox.Show("Registration successful");
}
}
}
}
I've fixed it up a little but it's still giving me a error for "sqlCmd.Connection = connectionString;" giving me a error on the connectionString part
The code shows following now
SqlCommand sqlCmd = new SqlCommand("UserAdd");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#First_Name", textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Last_Name", textBox2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Email_ID", textBox3.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Contact", textBox4.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Address", richTextBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Department", comboBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Username", textBox5.Text.Trim());
sqlCmd.Connection = connectionString;```
You add some code twice, it's redundant ...
So you have to do only this:
string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";
private void button1_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
if (textBox5.Text.Trim() + textBox6.Text.Trim() == "")
{
MessageBox.Show("Please fill mandatory fields");
return;
}
sqlCon.Open();
using (SqlCommand sqlCmd = new SqlCommand("UserAdd", sqlCon)) // you missed to pass connection to command
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#First_Name", textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Last_Name", textBox2.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Email_ID", textBox3.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Contact", textBox4.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Address", richTextBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Gender", radioButton1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#Department", comboBox1.Text.Trim()); // also I think here must be comboBox1.SelectedValue, not Text property
sqlCmd.Parameters.AddWithValue("#Username", textBox5.Text.Trim());
sqlCmd.ExecuteNonQuery();
}
}
MessageBox.Show("Registration successful");
}
catch(Exception e)
{
MessageBox.Show($"Error on SQL \"UserAdd\" procedure: {e.Message}");
}
}
You are mixing u everything here. You need to run the respective command in the respective connection. this line is also wrong connectionString.Open(); Also you have not provided Connection to sqlCmd.
I am new on c# and i am facing problem. i made two buttons, one for case another for credit card. when i click on button, my data is not inserting into ms access file.why is it not showing any error and how can i fix it ?
private void CashButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.Cash);
}
private void CreditCardButton_Click(object sender, EventArgs e)
{
SaveOrder((int)PaymentTypes.CreditCard);
}
private void SaveOrder(int paymentType)
{
try
{
string connstring = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (OleDbConnection conn = new OleDbConnection(connstring))
{
conn.Open();
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [Orders](OrderNummber,TransactionDate,ClientName,TotalAmount,PaymentType) VALUES(#OrderNummber,#TransactionDate,#ClientName,#TotalAmount,#PaymentType)",conn))
{
cmd.Parameters.AddWithValue("#OrderNummber",OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#TransactionDate",TransactionDateDateTimePicker.Value.Date);
cmd.Parameters.AddWithValue("#ClientName",ClientNameTextBox.Text);
cmd.Parameters.AddWithValue("#TotalAmount",Convert.ToDecimal(TotalAmountTextBox.Text));
cmd.Parameters.AddWithValue("#PaymentType", paymentType);
cmd.ExecuteNonQuery();
}
foreach (DataGridViewRow row in CartDataGridView.Rows)
{
using (OleDbCommand cmd = new OleDbCommand("INSERT INTO [OrdersItems](OrderNumber,Quantity,UnitPrice,TotalPrice) VALUES(#OrderNumber,#Quantity,#UnitPrice,#TotalPrice)", conn))
{
cmd.Parameters.AddWithValue("#OrderNumber", OrderNumberTextBox.Text);
cmd.Parameters.AddWithValue("#Quantity", Convert.ToInt16(row.Cells["Quantity"].Value));
cmd.Parameters.AddWithValue("#UnitPrice",Convert.ToDecimal(row.Cells["UnitPrice"].Value));
cmd.Parameters.AddWithValue("#TotalPrice", Convert.ToDecimal(row.Cells["TotalPrice"].Value));
cmd.ExecuteNonQuery();
}
}
MessageBox.Show("Order is processed successfully!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
}
}
Do it like this.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.OleDb;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ryan\Desktop\Coding\Microsoft Access\Northwind.mdb";
string fstName = textBox1.Text.Trim();
string lstName = textBox2.Text.Trim();
string adres = textBox3.Text.Trim();
OleDbCommand cmd = new OleDbCommand(#"INSERT INTO MyExcelTable (FName, LName, Address) VALUES (#FName, #LName, #Address)")
{
Connection = conn
};
conn.Open();
if (conn.State == ConnectionState.Open)
{
// you should always use parameterized queries to avoid SQL Injection
cmd.Parameters.Add("#FName", OleDbType.VarChar).Value = fstName;
cmd.Parameters.Add("#LName", OleDbType.VarChar).Value = lstName;
cmd.Parameters.Add("#Address", OleDbType.VarChar).Value = adres;
try
{
cmd.ExecuteNonQuery();
MessageBox.Show(#"Data Added");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show(#"Connection Failed");
}
}
}
}
This will definitely work. Just change the connection string and the variables to suit your needs.
I'm very new to C#, but doing some experiments on my own. I created a Database with 3 tables:
tbl_Student: IDCard, Sname, Ssurname
tbl_Course: CID, Cname
tbl_StudentClass: CID, IDCard.
There is a relationship between them. Database part I'm OK.
Now I created 2 forms. 1 Form fills the Course table. The other Form fills the Student table. In the Student Form, I have a combobox that lists the CourseName, reading from the Course Table. The Combobox is working fine.
The problem is that when I want to click the SAVE button, the StudentCourse table is filled using the IDCard and the CID according to what course the user choose from the combobox dropdown. I can fill the IDCard but don't know how to fill the CID, that is use the CID of the Course Name selected from the combobox....any help please?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace StudentClassApplication
{
public partial class frmCreateStudent : Form
{
SqlConnection con = new SqlConnection(#"Data Source=REUBEN-PC\MSSQLEXPRESS;Initial Catalog=StudentClass;Integrated Security=True");
public frmCreateStudent()
{
InitializeComponent();
FillCombobox();
}
private void SaveStudent_button1_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlCommand cmd1 = new SqlCommand("INSERT into tbl_Student (IDCard,Sname, Ssurname) values (#IDCard,#Sname,#Ssurname)", con);
//insert data into tbl_Student Table
cmd1.Parameters.AddWithValue("#IDCard", textBox1.Text);
cmd1.Parameters.AddWithValue("#Sname", textBox2.Text);
cmd1.Parameters.AddWithValue("#Ssurname", textBox3.Text);
cmd1.ExecuteNonQuery();
cmd1.Parameters.Clear();
SqlCommand cmd2 = new SqlCommand("INSERT into tbl_StudentClass (IDCard, CID) VALUES (#IDCard,#CID)", con);
//insert data into tbl_StudentClass Table
cmd2.Parameters.AddWithValue("#IDCard", textBox1.Text);
cmd2.Parameters.AddWithValue("#CID", comboBox1.SelectedValue);
cmd2.ExecuteNonQuery();
cmd2.Parameters.Clear();
con.Close(); //connection close here , that is disconnected from data source
MessageBox.Show("Student has been added ! ");
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection ! ");
}
}
private void frmCreateStudent_Load(object sender, EventArgs e)
{
}
public void FillCombobox()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("select * from tbl_Class");
SqlDataReader myreader;
try
{
con.Open();
myreader = cmd.ExecuteReader();
while (myreader.Read())
{
string cname = myreader.GetString(1);
comboBox1.Items.Add(cname);
}
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection ! ");
}
}
protected void comboBox1_DataBound(object sender, EventArgs e)
{
var value = comboBox1.SelectedValue;
}
}
}
You have a tbl_Course and a Form for courses, so I guess you have a class like:
class Course
{
public int CID { get; set; }
public string Name { get; set; }
}
Now, instead of filling the ComboBox just with the names of the courses, fill it with entire Course objects!
Something like this in the constructor:
comboBox.DataSource = GetCourses();
comboBox.DisplayMember = "Name";
where GetCourses() is similar to your FillCombobox() method:
private List<Course> GetCourses()
{
SqlCommand cmd = new SqlCommand
{
cmd.Connection = con;
cmd.CommandText = "select * from tbl_Class";
};
List<Course> courses = new List<Course>();
SqlDataReader myReader;
try
{
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
Course c = new Course
{
CID = myreader.GetInt32(0),
name = myreader.GetString(1)
};
courses.Add(c);
}
}
catch (Exception ex)
{
MessageBox.Show("Cannot open connection!");
}
finally
{
if (con != null)
con.Close();
}
return courses;
}
Then, in SaveStudent_button1_Click() change this line:
cmd2.Parameters.AddWithValue("#CID", comboBox1.SelectedValue);
in this way:
Course c = (Course)comboBox1.SelectedItem;
cmd2.Parameters.AddWithValue("#CID", c.CID);
This is my code behind for data update. But it is not updating in my database. Don't know why. Any suggestion pls.
I've check the database connection and it is working fine. I didn't declare the connection string using {..}.
Actually I didn't get any error message for the insert. I got an record update message. But in my database, it is not updating.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace StudentDataDisplay2
{
public partial class Form1 : Form
{
SqlConnection conn = new SqlConnection(#"Data Source=localhost;Initial Catalog=TestData;Integrated Security=True");
public Form1()
{
InitializeComponent();
this.Text = "Student Data Display Form";
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void display_data()
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "SELECT * from StudentDetails";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close();
}
private void btnInsert_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "INSERT INTO StudentDetails VALUES (#Name,#Subject)";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.Parameters.Add("#Subject", SqlDbType.NVarChar).Value = textBox2.Text; //add values in textbox2 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record added");
}
private void btnDisplay_Click(object sender, EventArgs e)
{
display_data();
}
private void btnDelete_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record deleted");
}
private void btnUpdate_Click(object sender, EventArgs e)
{
//conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "UPDATE StudentDetails SET Name = #Name WHERE Subject = #Subject";
cmd.Parameters.AddWithValue("#Name", textBox1.Text);
cmd.Parameters.AddWithValue("#Subject", textBox2.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Record updated!");
}
private void buttonSearch_Click(object sender, EventArgs e)
{
conn.Open();//establish connection
SqlCommand cmd = conn.CreateCommand();
//cmd.CommandType = CommandType.Text();
cmd.CommandText = "DELETE FROM StudentDetails WHERE Name= #Name";
cmd.Parameters.Add("#Name", SqlDbType.NVarChar).Value = textBox1.Text; //add values in textbox1 and store in db
cmd.ExecuteNonQuery();
conn.Close();
display_data();
MessageBox.Show("Search completed!");
}
}
}
Here is a sample image of the UI:
I'm working on a project that will import an Excel file and display the data to a DataGridView via Windows form. Importing the Excel file and displaying it in the DataGridView works fine, what I'm having issues is saving the data in the DataGridView as a bulk insert when I click on the Save button it shows an
Screenshot of the error:
An unhandled exception of type 'System.ArgumentException' occured in System.Data.dll
When I view details it shows :
No mapping exists from object type System.Windows.Forms.DataGridViewTextBoxColumn to a known managed provider native type.
Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
SAVE BUTTON CODE
private void btn_Save_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.Rows)
{
string constring = #"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
using(SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_prospects ([prospectid], [firstname], [lastname], [height], [weight], [age], [college])VALUES(#prospectid, #firstname, #lastname, #height, #weight, #age, #college)", con))
{
cmd.Parameters.AddWithValue("#prospectid", prospectidDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#firstname", firstnameDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#lastname", lastnameDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#height", heightDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#weight", weightDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#age", ageDataGridViewTextBoxColumn);
cmd.Parameters.AddWithValue("#college", collegeDataGridViewTextBoxColumn);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
MessageBox.Show("Successfully Saved!");
}
}
}
I also included the other codes below
BROWSE BUTTON CODE
private void btn_Browse_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
this.txt_Path.Text = openFileDialog1.FileName;
}
}
LOAD BUTTON CODE
private void btn_Load_Click(object sender, EventArgs e)
{
string PathConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txt_Path.Text + ";Extended Properties=\"Excel 8.0;HDR=Yes;\";";
OleDbConnection conn = new OleDbConnection(PathConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from [" + txt_Sheet.Text + "$]", conn);
DataTable DT = new DataTable();
myDataAdapter.Fill(DT);
dataGridView1.DataSource = DT;
}
I'm new on coding C# and trying to learn it, this will be my first application if ever, if anyone can help me what I need to do thanks in advance.
You can directly use SqlBulkCopy to write datatable to Sql Server, rather than doing it row by row.
string constring = #"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
using (var bulkCopy = new SqlBulkCopy(constring ))
{
bulkCopy.BatchSize = 500;
bulkCopy.NotifyAfter = 1000;
bulkCopy.DestinationTableName = "TableName";
bulkCopy.WriteToServer(dataTable);
}
There are various SqlBulkCopy constructors to pass SqlConnection and SqlTransaction as well.
you can get the values from each row like this
foreach (DataGridViewRow row in dataGridView.Rows)
{
// your code
cmd.Parameters.AddWithValue("#prospectid",row.Cells["ColumnName"].Value.ToString());
}
My first remark: use only 1 times the object SqlConnextion and it is better now to add SqlTransaction object to avoid the partial recording of data in case of error on a line of DataGridView.
for the answer you need to specify the value of the cell of each column
private void btn_Save_Click(object sender, EventArgs e)
{
string constring = #"Data Source=databasename;Initial Catalog=Rookies;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlTransaction transaction = con.BeginTransaction();
try
{
con.Open();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO tbl_prospects ([prospectid], [firstname], [lastname], [height], [weight], [age], [college])VALUES(#prospectid, #firstname, #lastname, #height, #weight, #age, #college)", con))
{
cmd.Parameters.AddWithValue("#prospectid", row.Cells["prospectid"].Value);
cmd.Parameters.AddWithValue("#firstname", row.Cells["firstname"].Value);
cmd.Parameters.AddWithValue("#lastname", row.Cells["lastname"].Value);
cmd.Parameters.AddWithValue("#height", row.Cells["height"].Value);
cmd.Parameters.AddWithValue("#weight", row.Cells["weight"].Value);
cmd.Parameters.AddWithValue("#age", row.Cells["age"].Value);
cmd.Parameters.AddWithValue("#college", row.Cells["college"].Value);
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
}
}
transaction.Commit();
con.Close();
MessageBox.Show("Successfully Saved!");
}
catch (Exception ex)
{
transaction.Rollback();
con.Close();
MessageBox.Show(ex.Message);
}
}
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txtSearsh.Text != "")
{
if (dataGridView1.Rows.Count > 0)
{
for (int i = 0; i < dataGridView1.Rows.Count ; i++)
{
COI.INSERTdATA(txtSearsh.Text,
dataGridView1.CurrentRow.Cells["COIL_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SLAB_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["ORDER_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["ORDER_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["ITEM_NO"].Value.ToString(),
dataGridView1.CurrentRow.Cells["PROD_TYPE"].Value.ToString(),
dataGridView1.CurrentRow.Cells["GRADE"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_THICK"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_WIDTH"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_LENGTH"].Value.ToString(),
dataGridView1.CurrentRow.Cells["SL_WGHT"].Value.ToString(),
dataGridView1.CurrentRow.Cells["C_THICK"].Value.ToString(),
dataGridView1.CurrentRow.Cells["C_WIDTH"].Value.ToString(),
dataGridView1.CurrentRow.Cells["C_WT"].Value.ToString(),
dataGridView1.CurrentRow.Cells["PRODUCED"].Value.ToString(), "", "", "", "", "", "", DTP.Value, "", "", "", "", "", ""
);
}
MessageBox.Show("SaccessFouly");
}
else { MessageBox.Show("أدخل رقم البرنامج"); }
}
}