Advertisement
NAK

SqlDataReader simple (C#)

NAK
Dec 10th, 2013
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 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.         public DataTable  FillData(string strConnection, string SQLQuery)
  31.         {
  32.             DataTable dt = new DataTable();
  33.             // declare the SqlDataReader, which is used in
  34.             SqlDataReader rdr = null;
  35.  
  36.             // create a connection object
  37.             using (SqlConnection conn = new SqlConnection(strConnection))
  38.             {
  39.                 conn.Open();
  40.                 SqlCommand cmd = new SqlCommand(SQLQuery, conn);
  41.                 // get an instance of the SqlDataReader
  42.                 using (SqlDataReader reader = cmd.ExecuteReader())
  43.                 {
  44.                     // create a command object
  45.                     try
  46.                     {
  47.                         // fill the DataTable
  48.                         dt.Load(reader);
  49.                     }
  50.                     catch (Exception)
  51.                     {
  52.                     }
  53.                 }
  54.             }
  55.             // return the DataTable
  56.             return dt;
  57.         }
  58.  
  59.  
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement