Advertisement
andrzejiwaniuk

Podlaczenie i pobranie danych z bazy danych SQL Servera

Oct 2nd, 2014
880
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows;
  7. using System.Windows.Controls;
  8. using System.Windows.Data;
  9. using System.Windows.Documents;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Navigation;
  14. using System.Windows.Shapes;
  15. using System.Data;
  16. using System.Data.SqlClient;
  17.  
  18. namespace baza_danych1
  19. {
  20.     /// <summary>
  21.     /// Interaction logic for MainWindow.xaml
  22.     /// </summary>
  23.     public partial class MainWindow : Window
  24.     {
  25.         public MainWindow()
  26.         {
  27.             InitializeComponent();
  28.         }
  29.  
  30.         private void Button_Click(object sender, RoutedEventArgs e)
  31.         {
  32.             logowanie_do_bazy();
  33.         }
  34.         private void logowanie_do_bazy()
  35.         {
  36.             string select = "SELECT * FROM nazwa_twojej_tabeli";     //nazwa_twojej_tabeli <- zastąp swoją nazwą
  37.  
  38.             string connetionString = null;
  39.             SqlConnection cnn;
  40.            
  41.         //należy odpowiednio wpisać swoją nazwe komputera, nazwe bazy danych oraz haslo
  42.         connetionString = "Data Source=LAPTOP-PC\\SQLEXPRESSDEV;Initial Catalog=nazwa_twojej_bazy;User ID=sa;Password=haslo";
  43.             cnn = new SqlConnection(connetionString);
  44.             try
  45.             {
  46.                 cnn.Open();
  47.                 MessageBox.Show("Podłączony do serwera MS SQL 2014 ! ");
  48.  
  49.                 // wyswietlenie danych na datagridview
  50.  
  51.  
  52.                 SqlDataAdapter dataAdapter = new SqlDataAdapter(select, cnn); //c.con is the connection string
  53.  
  54.                 SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
  55.                 DataSet ds = new DataSet();
  56.                 DataTable dt = new DataTable("Pracownicy");
  57.  
  58.                 dataAdapter.Fill(dt);
  59.                 dataGridView1.ItemsSource = dt.DefaultView;
  60.                 //dataGridView1.ReadOnly = true;
  61.  
  62.  
  63.                 //---
  64.                 cnn.Close();
  65.             }
  66.             catch (Exception ex)
  67.             {
  68.                 MessageBox.Show("Problem z podłączeniem do serwera bazy danych MS SQL ! ");
  69.             }
  70.         }
  71.  
  72.      }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement