Berikut adalah cara koneksi SQL Server dengan Visual C#
1. Buat tampilan seperti dibawah ini :
tambahkan 4 label dengan nama, 4 Textbox, 2 button seperti gambar
lalu isikan sintak :
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 SqlServerConnection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOK_Click(object sender, EventArgs e)
{
try
{
SqlConnection SqlConn = new SqlConnection();
SqlConn.ConnectionString = "Data Source=" + txtServer.Text + ";" +
"Initial Catalog=" + txtInitialCatalog.Text + ";" +
"User Id=" + txtUserID.Text + ";" +
"Password=" + txtPassword.Text + ";";
if (SqlConn.State == ConnectionState.Open) SqlConn.Close();
SqlConn.Open();
MessageBox.Show("Koneksi Berhasil", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show("Koneksi Gagal, " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}
Jalankan tekan F5, kemudian isikan data, lalu klik OK