Hello everyone, in this article I will share with you about creating a connection database using ADO.Net. Let's follow the steps below.
Step 1
First, you have to prepare database and tables. In this practice, I use database SQL Server. The database name is "dbAdmSekolah", and I have table, one of which is named "tbl_Agama".
Step 2
Second, create a new project in Visual Studio. Then, create UI design like below.
Step 3
Next, create connection to database SQL Server. You can open Server Explore tab --> right click on Data Connections --> and choose Add Connection. Fill on Server Name and select a database name --> then click OK button
Step 4
Back to Form Agama UI design, now you can right click and choose View Code or you can click F7 button on the keyboard.
Step 5
Declare string connection
public partial class Form_Agama: Form {
//deklarasi koneksi string
private string conStr = "Data Source=(local); " + "Initial Catalog=dbAdmSekolah; Integrated Security=True";
private SqlConnection conn;
public Form_Agama() {
InitializeComponent();
conn = new SqlConnection(conStr);
}
}
Step 6
And then create TampilDataAgama method like below.
private void tampilDataAgama() {
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM tbl_Agama";
DataSet ds = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(ds, "tbl_Agama");
dgAgama.DataSource = ds;
dgAgama.DataMember = "tbl_Agama";
conn.Close();
}
Step 7
Then call the method on the main form
private void Form_Agama_Load(object sender, EventArgs e) {
tampilDataAgama();
}
Step 8
Click on Start to show the result.
Step 9
Finished
If you have any questions, please write them in the comments column.