Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (1 vote)
1K views

Csharp Connect To SQL Server PDF

This document provides steps to connect a C# application to a local SQL Server database. It describes: 1. Creating a Windows Forms project in Visual Studio and adding a database file (.mdf) to the project. 2. Using Server Explorer to create a table in the database with username and password fields. 3. Binding the Windows Form controls like textboxes and a datagridview to the database tables to view and edit data. 4. Adding code to navigate records using the bindingsource and perform add/update operations.

Uploaded by

yeshi janexo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
1K views

Csharp Connect To SQL Server PDF

This document provides steps to connect a C# application to a local SQL Server database. It describes: 1. Creating a Windows Forms project in Visual Studio and adding a database file (.mdf) to the project. 2. Using Server Explorer to create a table in the database with username and password fields. 3. Binding the Windows Form controls like textboxes and a datagridview to the database tables to view and edit data. 4. Adding code to navigate records using the bindingsource and perform add/update operations.

Uploaded by

yeshi janexo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

DMU C# HKA

C# SQL Server Connection

You can connect your C# application to data in a SQL Server database using
the .NET Framework Data Provider for SQL Server. We can have to
approaches to connect to SQL server database.

1. To connect our C# to a local server


2. To connect our C# to an existing SQL server database

To connect our C# to a local server

1. Open visual studio and create a new project

Select your windows form application and give appropriate name for
your project. Please don’t leave it empty or ambiguous name like
WindowsFormsApp12. Look My project name:

1
DMU C# HKA

2. Create your database being on the visual studio interface, and create
your tables as appropriate. On my case I created a database named
Accounts and a table login.

A. Right Click on your project name (“Connect Local Database”) and add
new item

B. Among the available list opened as new item select “server-Based


Database” and write your database name (Accounts.mdf) click Add

2
DMU C# HKA

C. Now you have already created your database. Look your solution
explorer and your new database Accounts.mdf is added.

D. Now you are supposed to create your tables this is done on the Server
Explorer. To access the Server Explorer either double click on the
database name that you have seen above on the solution explorer or

click on the view tab then to get the Server Explorer.

3. Create Table Login

A. Right click on the Tables and click on Add New Table

3
DMU C# HKA

The next step take some time according to the speed of your computer this is
because SQL server to be integrated locally may take some minutes according
to the speed and performance of your computer. (Be Patient until SQL Server
loads)

i. Name your Table Login


ii. Then fill your fields (on this case Username and Password)
with
iii. Appropriate datatype (do this either on the design window on
the top or query window on the bottom)
iv. Assign Primary key if needed (on my case no primary key)

v. Click on Update to save your table designed


(as you look on step 2 of the following diagram)

At this moment you have created your table login

4
DMU C# HKA

4. Fill your tables with records

Right click on your table (Login) and click on show table data. This is
similar to selecting top 1000rwos in SQL server for editing

You can fill any record as username and Password

5. Design queries on your tables

To design queries for your database right click on your table and click
on New Query

5
DMU C# HKA

After writing your queries execute (on No 2 below) them

a. Such as inserting records

 INSERT INTO dbo.Login ( Username, Password)VALUES(


'Abebe', 'Pass1'
),('Alemu','Pass2'),('kebede','pass3'),('Almaz','Pass4')

b. Selecting records

 SELECT * FROM dbo.Login;


 SELECT * FROM dbo.Login WHERE password LIKE'p%';
 SELECT * FROM dbo.Login WHERE Username='Hale';

6. Creating views on your local database, create whatever views you


want and click on update to save your views.

6
DMU C# HKA

CREATE VIEW [dbo].[UserPass] AS SELECT * FROM dbo.Login WHERE


Password LIKE 'pass%'

Or you can write SQL Query for executing your views

 SELECT * FROM UserPass

7. Design your interface

Now return back to your visual studio interface and design the buttons
for navigation or drag and drop the textboxes from your data source.

 Two Labels
 Two Textboxes: for username and Password
 Four Buttons for Navigation
 One Data Grid View for looking all you records

8. Connect your interface to your local database using databinding source

A. Click on Data on the Toolbox and binding source

7
DMU C# HKA

B. Rename you binding source if you want. On the property windows


provide your DataSource on clicking the Datasource and “Adding
Project Data Source”

Then follow the wizard to connect your SQL database you have created earlier
to your interface designed

C. Select Database and click on Next

8
DMU C# HKA

D. Select your dataset and click Next

E. At this moment your database should be shown on the connnection


string

F. If your database is seen on the New Connection text box


(Accounts.mdf) click on Next
Name your connection string and click Next
9
DMU C# HKA

G. Select what you want to be loaded on your database it can be Tables,


Views, Stored Procedures etc. then click on Finish

Now your databinding is connected to your interface so, return back and click
ok. On the data sources you can see your accounts Dataset you have created
earlier

10
DMU C# HKA

 You can do two things now. Both ways work perfect. The first
approaches takes time to provide data sources. While the second
approach automatically put linked textboxes on the form.
o On the property window either set your textbox1 and
textbox2 with proper Data Source giving the text as follows. On
the DataBindings UserName textbox1 and Password for
textbox2

Or
o You can drag and drop the details on your form if you have not
put textbox1 and textbox2 earlier

11
DMU C# HKA

Then Drag and drop your login table with the fields on the form. It will
automatically put the label and text boxes on the form.

You can see your data grid view is also set with data source
(bindingSource1) and data member (Login).

Now let’s start testing if it works. Run your project and all of the three sources
should be filled with your database data. If so successful you have populated
your interface with values from the local database.
 Number 1 is designed textboxes where we provide the data source
 Number 2 is the drag and dropped from our data source
 Number 3 is the data grid view where the data source and member
are set above

12
DMU C# HKA

Navigate through your records (Moving forward and backward)


Let us see how to navigate through records. On the above interface we have
four buttons to work with. First, Previous, Next and Last.
Click each of them and put the following codes using the data binding source
to bindingsource1 navigate that is.

private void btnFirst_Click(object sender, EventArgs e)


{
bindingSource1.MoveFirst();
}

private void btnPrevious_Click(object sender, EventArgs e)


{
bindingSource1.MovePrevious();
}

13
DMU C# HKA

private void btnNext_Click(object sender, EventArgs e)


{
bindingSource1.MoveNext();

private void btnLast_Click(object sender, EventArgs e)


{
bindingSource1.MoveLast();
}
private void btnAddnew_Click(object sender, EventArgs e)
{
if (btnAddnew.Text == "Add New")
{
bindingSource1.AddNew();
btnAddnew.Text = "Update";
btnFirst.Enabled = false;
btnLast.Enabled = false;
btnPrevious.Enabled = false;
btnNext.Enabled = false;
}
else
{

btnAddnew.Text = "Add New";


btnFirst.Enabled = true;
btnLast.Enabled = true;
btnPrevious.Enabled = true;
btnNext.Enabled = true;

14
DMU C# HKA

9. What do you see on the following image?

Exercise

10. Adding new record (already done above), Updating and Deleting,
searching records should be added on the above button.

Publishing your project

15
DMU C# HKA

Provide your Project Location

Install the above file to your computer

Or open you project and copy paste the Debug folder to the place you
want.

Advantage of Local Database

Therefore it is easy to move your database and project together. You can
easily take it to another computer without worrying about your SQL server
database.

To connect our C# to an existing SQL server


database
The first step in a C# application is to create an instance of the Server object
and to establish its connection to an instance of Microsoft SQL Server.

The SqlConnection Object is Handling the part of physical communication


between the C# application and the SQL Server Database. An instance of the
SqlConnection class in C# is supported the Data Provider for SQL Server
Database. The SqlConnection instance takes Connection String as argument
and pass the value to the Constructor statement. Follow the steps below to
get your database connected to your C# application.

1. Create your Database on SQL server


 Look the name if your SQL Server - USER: This will be important
while you connect to your visual studio latter on
 Look the Name of Your Database – Stud
 Look the name of your Table – department

16
DMU C# HKA

Fill with some Data Like:

Close your SQL Server.

2. Open your new Visual studio

Select Windows Form Application and provide name (connect SQL


Server) and location of your Project

17
DMU C# HKA

3. Add the following line to your name space


Aadding data.SqlClient enables you to use the SQL connection string to
your database
using System.Data.SqlClient;

4. Add a data grid view to your form. This is from your toolbox and
Data group. The data grid view is used to see the full table with its
records.
Also Add different buttons to Manipulate records (Adding, viewing,
deleting updating, searching etc..)
Also Add different Textboxes to submit text values

5. Connect your database from SQL Server


a. Click on your Server Explorer

18
DMU C# HKA

b. Click connect To A Database


c. Now change your connection from OLEDB to SQL server

d. After selecting SQL server and the Data provider: is SQL server
too, click OK

e. Now look your Data Source is the SQL Client


f. Your Database name is your SQL server database name on step
1 above - USER
g. Among the lists your database is Stud
h. Test your database connection it should be successful.

19
DMU C# HKA

6. While you look your server Explorer your stud database should be
populated with department Table too.

20
DMU C# HKA

7. Double click on you visual studio form and write the following. To get
your SqlConnection click on your database and copy the path from your
Connection String on the property windows (circle No 2 on the diagram
below)

private void Form1_Load(object sender, EventArgs e)


{
SqlConnection sqlcn = new SqlConnection("Data Source=user;Initial
Catalog=stud;Integrated Security=True");
SqlDataAdapter adp = new SqlDataAdapter("select * from department",
sqlcn);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridView1.DataSource = dt;
}

Now Start your project after building the DataGridView1 should be filled
with all records from your department Table.

21
DMU C# HKA

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 connect_SQL_Server
{
public partial class Form1 : Form
{
SqlConnection sqlcn = new SqlConnection("Data Source=user;Initial
Catalog=stud;Integrated Security=True");

public Form1()
{
InitializeComponent();
}

private void btnView_Click(object sender, EventArgs e)


{
sqlcn.Open();
SqlCommand cmd = sqlcn.CreateCommand();
cmd.CommandType = CommandType.Text;
SqlDataAdapter adp = new SqlDataAdapter("select * from dbo.department",
sqlcn);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridView1.DataSource = dt;
sqlcn.Close();
}

private void btnAddNew_Click(object sender, EventArgs e)


{
sqlcn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into dbo.department values
('Maths','Bure','114')";

22
DMU C# HKA

cmd.Connection = sqlcn;
cmd.ExecuteNonQuery();
sqlcn.Close();
MessageBox.Show("Record inserted");

}
private void btnDelete_Click(object sender, EventArgs e)
{
MessageBox.Show("Do you want to Delete ?", "Delete Record",
MessageBoxButtons.OKCancel);
if (true)
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "delete from dbo.department where
dname=('"+textBox1.Text+"')";
cmd.Connection = cn;
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record deleted ");
}
else
{
MessageBox.Show("Not Deleted");
}
}
}
}

However
 Whether we publish our project to be an .EXE file or
 Copy the Debug folder like we did on local database we cannot
easily move this project to other machines because the database
is still attached to the SQL server. You can look these two
different folders below. One already has the database but this
project doesn’t include the database file.

23
DMU C# HKA

=/=

24

You might also like