Programming for Everybody: sql server
Showing posts with label sql server. Show all posts
Showing posts with label sql server. Show all posts

Connect VB.NET to Local SQL Database in Visual Studio 2026 (With Source Code)



Imports System.Data.SqlClient
Public Class Form1
Dim conn2 As New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;initial catalog=database2;Integrated Security=True")
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim conn As New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Integrated Security=True")
Dim strsql As String = "If Not Exists(Select name from sys.databases Where name='database2')" &
" begin create database database2 select 1 end" &
" else begin select 0 end"
Dim cmd As New SqlCommand(strsql, conn)
conn.Open()
Dim result As Integer = Convert.ToInt32(cmd.ExecuteScalar())
If result = 1 Then
MessageBox.Show("Database created Successfully")
Else
MessageBox.Show("Database already exists")
End If
conn.Close()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim strsql As String = "If Not Exists(Select name From sys.tables Where name='students') " &
"begin create table students(id int primary key identity(1,1)," &
"name1 varchar(50) Not Null," &
"phone varchar(50) Not Null," &
"date1 date Not Null) Select 1 end " &
" else begin select 0 end"
Dim cmd As New SqlCommand(strsql, conn2)
conn2.Open()
Dim result As Integer = Convert.ToInt32(cmd.ExecuteScalar())
If result = 1 Then
MessageBox.Show("Table created Successfully")
Else
MessageBox.Show("Table already exists")
End If
conn2.Close()

End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
load_data()
End Sub
Private Sub load_data()
conn2.Open()
Dim da As New SqlDataAdapter("Select * From students", conn2)
Dim dt As New DataTable
da.Fill(dt)
DataGridView1.DataSource = dt
conn2.Close()
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
TextBox1.Text = ""
TextBox2.Text = ""
DateTimePicker1.Value = Now()
Button4.Enabled = True
End Sub

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim cmd As New SqlCommand("Insert Into students(name1,phone,date1)Values(@name1,@phone,@date1)", conn2)
cmd.Parameters.AddWithValue("name1", TextBox1.Text.Trim)
cmd.Parameters.AddWithValue("phone", TextBox2.Text.Trim)
cmd.Parameters.AddWithValue("date1", DateTimePicker1.Value.ToString)
conn2.Open()
cmd.ExecuteNonQuery()
conn2.Close()
Button4.Enabled = False
load_data()
End Sub 

End Class 

insert update delete search and print in sql server databse using C# [with Source 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.SqlClient;

namespace Insert_update_delete_search_and_print_in_sql

{

    public partial class Form2 : Form

    {

        public Form2()

        {

            InitializeComponent();

        }

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

        private void Form2_Load(object sender, EventArgs e)

        {

            bind_data();

        }

        private void bind_data()

        {

            SqlCommand cmd1 = new SqlCommand("Select id,fname As firstname,lname As Lastname,sum from Table1", conn);

            SqlDataAdapter da = new SqlDataAdapter();

            da.SelectCommand = cmd1;

            DataTable dt = new DataTable();

            dt.Clear();

            da.Fill(dt);

            dataGridView1.DataSource = dt;

            dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 12, FontStyle.Bold);

            dataGridView1.DefaultCellStyle.Font = new Font("arial", 12);

        }


        private void button1_Click(object sender, EventArgs e)

        {

            SqlCommand cmd2 = new SqlCommand("Insert into Table1(id,fname,lname,sum)Values(@id,@firstname,@lastname,@sum)", conn);

            cmd2.Parameters.AddWithValue("id", textBox1.Text);

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

            cmd2.Parameters.AddWithValue("lastname", textBox3.Text);

            cmd2.Parameters.AddWithValue("sum", textBox4.Text);

            conn.Open();

            cmd2.ExecuteNonQuery();

            conn.Close();

            bind_data();


        }


        private void button2_Click(object sender, EventArgs e)

        {

            textBox1.Text = "";

            textBox2.Text = "";

            textBox3.Text = "";

            textBox4.Text = "";


        }


        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

        {

            int index;

            index = e.RowIndex;

            DataGridViewRow selectedrow = dataGridView1.Rows[index];

            textBox1.Text = selectedrow.Cells[0].Value.ToString();

            textBox2.Text = selectedrow.Cells[1].Value.ToString();

            textBox3.Text = selectedrow.Cells[2].Value.ToString();

            textBox4.Text = selectedrow.Cells[3].Value.ToString();



        }


        private void button3_Click(object sender, EventArgs e)

        {

            SqlCommand cmd3 = new SqlCommand("Update Table1 Set fname=@firstname,lname=@lastname,sum=@sum where id=@id", conn);


            

            cmd3.Parameters.AddWithValue("firstname", textBox2.Text);

            cmd3.Parameters.AddWithValue("lastname", textBox3.Text);

            cmd3.Parameters.AddWithValue("sum", textBox4.Text);

            cmd3.Parameters.AddWithValue("id", textBox1.Text);

            conn.Open();

            cmd3.ExecuteNonQuery();

            conn.Close();

            bind_data();

        }


        private void button4_Click(object sender, EventArgs e)

        {

            SqlCommand cmd4 = new SqlCommand("Delete from Table1 where id=@id", conn);

            cmd4.Parameters.AddWithValue("id", textBox1.Text);

            conn.Open();

            cmd4.ExecuteNonQuery();

            conn.Close();

            bind_data();

        }


        private void button5_Click(object sender, EventArgs e)

        {

            SqlCommand cmd1 = new SqlCommand("Select id,fname As firstname,lname As Lastname,sum from Table1 where fname Like @firstname+'%'", conn);

            cmd1.Parameters.AddWithValue("firstname", textBox5.Text);

            SqlDataAdapter da = new SqlDataAdapter();

            da.SelectCommand = cmd1;

            DataTable dt = new DataTable();

            dt.Clear();

            da.Fill(dt);

            dataGridView1.DataSource = dt;

            dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Tahoma", 12, FontStyle.Bold);

            dataGridView1.DefaultCellStyle.Font = new Font("arial", 12);

        }


        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)

        {

            Bitmap imagebmp = new Bitmap(dataGridView1.Width, dataGridView1.Height);

            dataGridView1.DrawToBitmap(imagebmp, new Rectangle(0, 0, dataGridView1.Width, dataGridView1.Height));

            e.Graphics.DrawImage(imagebmp, 120, 20);

        }


        private void button6_Click(object sender, EventArgs e)

        {

            printPreviewDialog1.Document = printDocument1;

            printPreviewDialog1.PrintPreviewControl.Zoom = 1;

            printPreviewDialog1.ShowDialog();

        }

    }

}

VB. net Tutorial import data from Excel to SQL server

 Imports System.Data.OleDb

Imports System.Data.SqlClient

Public Class Form15

    Private Sub Form15_Load(sender As Object, e As EventArgs) Handles Me.Load

        Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" &

         "Data Source=F:\names2.xlsx;Extended Properties= 'Excel 8.0;HDR=False'")

        conn.Open()

        Dim cmd As New OleDbCommand("Select * from [sheet4$]", conn)

        Dim da As New OleDbDataAdapter

        da.SelectCommand = cmd

        Dim dt As New DataTable

        dt.Clear()

        da.Fill(dt)

        DataGridView1.DataSource = dt

        conn.Close()

    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim conn2 As New SqlConnection("Data source=.;initial catalog=names2;integrated security=true")

        For Each row As DataGridViewRow In DataGridView1.Rows

            Dim cmd2 As New SqlCommand("Insert into table2(id,name1,age,telephone)Values(@id,@name1,@age,@telephone)", conn2)

            cmd2.Parameters.AddWithValue("id", row.Cells("id").Value.ToString)

            cmd2.Parameters.AddWithValue("name1", row.Cells("name1").Value.ToString)

            cmd2.Parameters.AddWithValue("age", row.Cells("age").Value.ToString)

            cmd2.Parameters.AddWithValue("telephone", row.Cells("telephone").Value.ToString)

            conn2.Open()

            cmd2.ExecuteNonQuery()

            conn2.Close()

        Next

        MessageBox.Show("All Data inserted successfully")

    End Sub

End Class



(create,delete,restore and backup database) and create,delete and display data in tables Sql server

 This program include(display databases and tables- display content tables and insert,update and Remove data- Create new database- delete database- backup database- restore database-Create new table by code)




How to insert image into a SQL database using Visual Basic.net(with Source Code+database)











Imports System.Data.SqlClient
Imports System.IO
Imports System.Drawing.Imaging

Public Class Form2


    Dim con1 As New SqlConnection("Server=.;Database=images;integrated security=true")

    Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        bind1()
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click


        Dim openfiledialog1 As New OpenFileDialog


        openfiledialog1.Filter = "images|*.jpg;*.png;*.gif;*.bmp"


        If openfiledialog1.ShowDialog = Windows.Forms.DialogResult.OK Then



            PictureBox1.Image = Image.FromFile(openfiledialog1.FileName)


        End If

    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click


        Dim command1 As New SqlCommand("Insert into table1(name,age,img1)values(@name,@age,@img)", con1)

        command1.Parameters.Add("@name", SqlDbType.VarChar).Value = TextBox1.Text


        command1.Parameters.Add("@age", SqlDbType.VarChar).Value = TextBox2.Text



        Dim memstr As New MemoryStream


        PictureBox1.Image.Save(memstr, PictureBox1.Image.RawFormat)

        command1.Parameters.Add("@img", SqlDbType.Image).Value = memstr.ToArray


        If con1.State = ConnectionState.Closed Then

            con1.Open()


        End If

        command1.ExecuteNonQuery()

        MessageBox.Show("image inserted")

        con1.Close()

        bind1()

    End Sub


    Private Sub bind1()

        Dim command1 As New SqlCommand("Select * from table1 order by id desc", con1)


        Dim adapter As New SqlDataAdapter(command1)


        Dim table As New DataTable()

        adapter.Fill(table)

        DataGridView1.AllowUserToAddRows = False

        DataGridView1.RowTemplate.Height = 90


        Dim pic1 As New DataGridViewImageColumn

        DataGridView1.DataSource = table

        pic1 = DataGridView1.Columns(3)

        pic1.ImageLayout = DataGridViewImageCellLayout.Stretch


    End Sub



    Private Sub DataGridView1_Click(sender As Object, e As System.EventArgs) Handles DataGridView1.Click


        Label4.Text = DataGridView1.CurrentRow.Cells(0).Value

        TextBox1.Text = DataGridView1.CurrentRow.Cells(1).Value


        TextBox2.Text = DataGridView1.CurrentRow.Cells(2).Value



        Dim img As Byte()

        img = DataGridView1.CurrentRow.Cells(3).Value

        Dim memstr As New MemoryStream(img)


        PictureBox1.Image = Image.FromStream(memstr)




    End Sub

    Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click


        Dim memstr As New MemoryStream

        PictureBox1.Image.Save(memstr, PictureBox1.Image.RawFormat)


        Dim img() As Byte

        img = memstr.ToArray()

        Dim update1 As String = "Update table1 set name='" & TextBox1.Text & "',age='" & TextBox2.Text & "',img1=@img where id=" & Label4.Text

        Dim command1 As New SqlCommand(update1, con1)

        command1.Parameters.Add("@img", SqlDbType.Image).Value = img

        If con1.State = ConnectionState.Closed Then

            con1.Open()
        End If

        command1.ExecuteNonQuery()

        MessageBox.Show("Image updated")

        con1.Close()

        bind1()

    End Sub

    Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click


        Dim delete1 As String = "Delete from table1 where id=" & Label4.Text

        Dim command1 As New SqlCommand(delete1, con1)

        If con1.State = ConnectionState.Closed Then

            con1.Open()

        End If

        command1.ExecuteNonQuery()

        MessageBox.Show("Image deleted")


        con1.Close()


        bind1()


    End Sub
End Class

How to attach database mdf file in sql server and fix an error occurred when attaching the database

 How to attach database mdf file in sql server and fix an error occurred when attaching the databases, Click the hyperlink in the Message column for detail.






Visual Basic.net: get duplicate records in SQL Server[ with source code ]

 


Imports System.Data.SqlClient
Public Class Form1
    Dim conn As New SqlConnection("Data Source=.;Initial Catalog=Names;Integrated Security=True")
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If conn.State = ConnectionState.Closed Then
            conn.Open()

        End If

        Dim cmd1 As New SqlCommand("select * from table1 where name In (Select name from table1 Group by name having (Count(*)>1)) order by name", conn)

        Dim da As New SqlDataAdapter
        Dim dt As New DataTable
        da.SelectCommand = cmd1
        dt.Clear()
        da.Fill(dt)
        DataGridView1.DataSource = dt

        conn.Close()






    End Sub
End Class

C# : Create Login form in C# step by step [ with source code ]

 


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;


namespace login
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data source=.; initial catalog=users;integrated security=true");

            SqlCommand cmd = new SqlCommand("select * from login1 where user1=@user1 and pass1=@pass1", conn);

            cmd.Parameters.Add("@user1", SqlDbType.VarChar).Value = textBox1.Text;

            cmd.Parameters.Add("@pass1", SqlDbType.VarChar).Value = textBox2.Text;


            SqlDataAdapter adapter1 = new SqlDataAdapter(cmd);

            DataTable table = new DataTable();

            adapter1.Fill(table);

            if (table.Rows.Count == 1)
            {

                Form2 gg = new Form2();

                gg.Show();

                this.Hide();

            }
            else
            {
                MessageBox.Show("Error username or password");


            }



        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {

            if (checkBox1.Checked == true)
            {
                textBox2.UseSystemPasswordChar = false;
            }
            else
            {

                textBox2.UseSystemPasswordChar = true;
            }



        }
    }

    }

Connect SQL server database with Visual Studio C# [ with source code ]

 



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'names1DataSet.Table1' table. You can move, or remove it, as needed.
            this.table1TableAdapter.Fill(this.names1DataSet.Table1);

            


        }

        private void button1_Click(object sender, EventArgs e)
        {
            table1BindingSource.AddNew();

        }

        private void button2_Click(object sender, EventArgs e)
        {
            table1BindingSource.EndEdit();
            table1TableAdapter.Update(names1DataSet.Table1);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            table1BindingSource.RemoveCurrent();
    table1TableAdapter.Update(names1DataSet.Table1);

        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();

        }

        private void button5_Click(object sender, EventArgs e)
        {
            table1BindingSource.MoveFirst();

        }

        private void button6_Click(object sender, EventArgs e)
        {
            table1BindingSource.MoveLast();

        }

        private void button7_Click(object sender, EventArgs e)
        {
            table1BindingSource.MovePrevious();

        }

        private void button8_Click(object sender, EventArgs e)
        {
            table1BindingSource.MoveNext();

        }
    }
}