Programming for Everybody: December 2021

Programming in C# Insert data into sql Database and fix an error Violation of PRIMARY KEY



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 Insert_button2

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }


        private void button1_Click(object sender, EventArgs e)

        {

            SqlConnection conn = new SqlConnection("Data source=.;initial catalog=names3;integrated security=true");

            conn.Open();

            SqlCommand cmd2 = new SqlCommand("Select username from table2 where username=@username", conn);

            cmd2.Parameters.AddWithValue("username", textBox2.Text);

            SqlDataReader myreader = cmd2.ExecuteReader();

            if (myreader.Read())

            {


                conn.Close();

                MessageBox.Show("Duplicate username");

            }

            else

            {

                conn.Close();

                SqlCommand cmd = new SqlCommand("Insert into table2(name1,username)Values(@name1,@username)", conn);

                cmd.Parameters.AddWithValue("name1", textBox1.Text);

                cmd.Parameters.AddWithValue("username", textBox2.Text);

                conn.Open();

                cmd.ExecuteNonQuery();

                conn.Close();

                MessageBox.Show("Data inserted successfully");

            

            }

           

        }

    }

}

 

Create a Application to connect access database with C# - Complete Course

 


Contents:

Add controls to your form 00:00 Delete last blank row in datagridview 09:26 Browse button 09:42 Create table database 14:21 Add Dataset and relate it with controls 15:37 change columns header text datagridview 20:52 New button 23:16 Format DateTime column in a DataGridView 25:04 Save or update button 26:17 Search button 29:34 Reset button 32:26 Remove button 33:24 Previous button 34:16 Next button 34:48 First button 35:06 Last button 35:25 Close button 35:41