Advertisement
NAK

SqlDataAdapter simple (C#)

NAK
Dec 3rd, 2013
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1. // put a dataGridView1 control on your form
  2. // and don't forget to insert your SQL Connection string and SQL query into the code
  3.  
  4. using System;
  5. using System.Data;
  6. using System.Data.SqlClient;
  7. using System.Windows.Forms;
  8.  
  9. namespace WindowsFormsApplication1
  10. {
  11.     public partial class Form1 : Form
  12.     {
  13.         public Form1()
  14.         {
  15.             InitializeComponent();
  16.         }
  17.  
  18.         private void Form1_Load(object sender, EventArgs e)
  19.         {
  20.             try
  21.             {
  22.                 // Render data onto the screen
  23.                 dataGridView1.DataSource =  FillData("<Your SQL Connection String here>", "<Your SQL Query here>");
  24.             }
  25.             catch (Exception)
  26.             {
  27.             }
  28.         }
  29.  
  30.         DataTable FillData(string strConnection, string SQLQuery)
  31.         {
  32.             DataTable dt = new DataTable();
  33.             // Open connection
  34.             using (SqlConnection conn = new SqlConnection(strConnection))
  35.             {
  36.                 conn.Open();
  37.                 SqlCommand cmd = new SqlCommand(SQLQuery);
  38.                 // Create new DataAdapter
  39.                 using (SqlDataAdapter a = new SqlDataAdapter(cmd.CommandText, conn))
  40.                 {
  41.                     // Use DataAdapter to fill DataTable
  42.                     try
  43.                     {
  44.                         // fill the DataTable
  45.                         a.Fill(dt);
  46.                     }
  47.                     catch (Exception)
  48.                     {
  49.                     }
  50.                 }
  51.             }
  52.             // return the DataTable
  53.             return dt;
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement