Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // put a dataGridView1 control on your form
- // and don't forget to insert your SQL Connection string and SQL query into the code
- using System;
- using System.Data;
- using System.Data.SqlClient;
- using System.Windows.Forms;
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- try
- {
- // Render data onto the screen
- dataGridView1.DataSource = FillData("<Your SQL Connection String here>", "<Your SQL Query here>");
- }
- catch (Exception)
- {
- }
- }
- DataTable FillData(string strConnection, string SQLQuery)
- {
- DataTable dt = new DataTable();
- // Open connection
- using (SqlConnection conn = new SqlConnection(strConnection))
- {
- conn.Open();
- SqlCommand cmd = new SqlCommand(SQLQuery);
- // Create new DataAdapter
- using (SqlDataAdapter a = new SqlDataAdapter(cmd.CommandText, conn))
- {
- // Use DataAdapter to fill DataTable
- try
- {
- // fill the DataTable
- a.Fill(dt);
- }
- catch (Exception)
- {
- }
- }
- }
- // return the DataTable
- return dt;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement