using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace t1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection conObj = new SqlConnection(); SqlDataAdapter da; DataSet ds = new DataSet(); private void Form1_Load(object sender, EventArgs e) { String strCon = ""; String strPath = System.IO.Directory.GetCurrentDirectory(); strCon = "DataSource=.\\SQLEXPRESS;Initial Catalog=Northwind;Intergrated Security=True"; if(conObj.State==ConnectionState.Open) { conObj.Close(); } else { conObj.ConnectionString = strCon; conObj.Open(); } string strSQL ="SELECT Customer.*FROM Customer;"; da = new SqlDataAdapter(strSQL, conObj); ds.Tables.Clear(); da.Fill(ds, "MyQuery"); dataGridView1.DataSource = ds.Tables["MyQuery"]; } } }
strCon = "Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Intergrated Security=True";
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; // เพิ่มเนมสเปซที่จำเป็น namespace DatabaseProgrammingSQLServerEx { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection conObj = new SqlConnection(); SqlDataAdapter da; DataSet ds = new DataSet(); private void Form1_Load(object sender, EventArgs e) { string strCon = ""; string strPath = System.IO.Directory.GetCurrentDirectory(); // อ่านพาธที่อยู่ของแอพพลิเคชัน //กำหนดรูปแบบการติดต่ิกับฐานข้อมูล strCon = "Data Source=.\\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True"; if (conObj.State == ConnectionState.Open) //ตรวจสอบการติดต่อกับฐานข้อมูลว่าเปิดอยู่หรือไม่ { conObj.Close(); // ถ้าค้างไว้ให้ปิดก่อน } else { conObj.ConnectionString = strCon; //กำหนดส่วนติดต่ิกับฐานข้อมูล conObj.Open(); // เปิดการเชื่อมต่อข้อมูล } string strSQL = "SELECT Customers.* FROM Customers;"; //กำหนดการดึงข้อมูลที่ต้องการด้วยคำสั่ง SQL // string strSQL = "SELECT Customers.*, Customers.ID FROM Customers WHERE (((Customers.ID)=17));"; da = new SqlDataAdapter(strSQL, conObj); // เริ่มดึงข้อมูลด้วยออบเจ็กต์ DataAdapter // เติมข้อมูลลงไปในออบเจ็กต์ DataSet ds.Tables.Clear(); // เคลียร์ข้อมูลใน DataSet กรณีที่มีข้อมูลเดิมอยู่ da.Fill(ds, "MyQuery"); // เราสามารถตั้งชื่อส่วนที่ Fill เข้าไปได้ตามใจชอบ dataGridView1.DataSource = ds.Tables["MyQuery"]; //แสดงข้อมูลใน DataGridView } } }
เพื่อความปลอดภัยของเว็บบอร์ด ไม่อนุญาติให้แทรก แท็ก [img]....[/img] โดยการอัพโหลดไฟล์รูปจากที่อื่น เช่นเว็บไซต์ ฟรีอัพโหลดต่าง ๆ อัพโหลดแทรกรูปภาพ ให้ใช้บริการอัพโหลดไฟล์ของไทยครีเอท และตัดรูปภาพให้พอดีกับสกรีน เพื่อความโหลดเร็วและไฟล์ไม่ถูกลบทิ้ง