Lecture 5 2nd Course C#
Lecture 5 2nd Course C#
1
C# Objects (controls)
1-Command Search in DataGrid View
2-Command Insert into Table in Database
3-Copy data from one table to another table
2
Direct Insert Record in a Table
This is the easiest way to insert records into a table but I strongly avoid it because it is less secure than
parameterized query.
Syntax
or,
namespace StudentinfoSystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//connection string
SqlConnection con = new SqlConnection("Data source
=(localdb)\\ProjectsV13; Initial catalog=StudentDBSystem;Integrated
security=true");
private void Button3_Click(object sender, EventArgs e)
{
//command
con.Open();
SqlCommand cmd = new SqlCommand("select * from StudentInfo where
fname=@A", con);
cmd.Parameters.AddWithValue("@A",textBox1.Text);
3
sdr.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
con.Open();
//command
cmd.ExecuteNonQuery();
con.Close();
4
// Following command to update the info in data grid view (function of Show data)
button1.PerformClick();
MessageBox.Show("Data has been inserted");
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
textBox5.Text = "";
textBox7.Text = "";
comboBox1.Text = "";
}
else
{
MessageBox.Show("check the contains");
}
}
namespace InsertRecords
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;Initial Catalog=ComputerShop;Integrated Security=True");
//Replaced Parameters with Value
string query = "INSERT INTO Products (Name, Price, Date)
VALUES(@Name, @Price, @Date)";
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
5
cmd.ExecuteNonQuery();
Console.WriteLine("Records Inserted Successfully");
}
catch (SqlException e)
{
Console.WriteLine("Error Generated. Details: " + e.ToString());}
finally
{
con.Close();
} }}
using System;
using System.Data.SqlClient;
namespace InsertRecords
{
class Program
{
static void Main(string[] args)
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;Initial Catalog=ComputerShop;Integrated Security=True");
//Replaced Parameters with Value
6
string query = "INSERT INTO Items(Name,Price,Date) SELECT
Name,Price,Date FROM Products";
SqlCommand cmd = new SqlCommand(query, con);
try
{
con.Open();
cmd.ExecuteNonQuery();
Console.WriteLine("Records Inserted Successfully");
}
catch (SqlException e)
{
Console.WriteLine("Error Generated. Details: " +
e.ToString());
}
finally
{
con.Close();
Console.ReadKey();
}
}
}
}
Output