วันศุกร์ที่ 18 ตุลาคม พ.ศ. 2556

Method Query Return 1 only MS Access (Access)

Method Query Return 1 only MS Access (Access)

1.Method สำหรับ Return ค่ากลับ เป็น int หรือ String

            public int Query1(String is_sql)
                  {
                      try
                      {
                          cons.Open();

                          OleDbCommand cmd = cons.CreateCommand();
                          cmd.CommandText = is_sql;
                          return (Convert.ToInt32(cmd.ExecuteScalar().ToString()));
                      }
                      finally
                      {
                          cons.Close();
                      }  
        }

_________________

2.Method สำหรับ Return ค่ากลับ เป็น int หรือ String แต่รับ Parameter เป็น CMD 

        String sql1 = "select count(*) from employee e left  join emp_delete d on e.emp_id =  d.emp_id ";
                 sql1 = sql1 + "where d.emp_id  is  null and e.emp_id like ? ";


       Connectdb condb = new Connectdb();
       OleDbCommand CMD = new OleDbCommand(sql1, condb.reConnect()); // เรียกหาตัวแปล Con
       CMD.Parameters.Add(new OleDbParameter("emp_id", OleDbType.VarChar)).Value = txtCode.Text;
       int chk = condb.Query1(CMD); // นำค่าไปตรวจสอบ

__________

        public int Query1(OleDbCommand cmd)
                {
                    try
                    {
                        cons.Open();
                        return (Convert.ToInt16(cmd.ExecuteScalar().ToString()));
                    }
                    finally
                    {
                        cons.Close();
                    }
                }
_________________________

3. ใช้ OleDbDataReader มาช่วยในการรับข้อมูล แล้ว Return กลับไป 1 ค่า วิธีนี้ไม่แนะนำ เพราะ ExecuteReader ไว้รับค่ามากกว่า 1 ค่า 

public int checkdb(String is_sql)
           {
               int count1 = 0;
               cons.Open();
       
               OleDbDataReader reader;
               OleDbCommand cmd = cons.CreateCommand();
               cmd.CommandText = is_sql;
               reader = cmd.ExecuteReader();
               while (reader.Read())
               {
                  int count1 = Convert.ToInt32(reader[0].ToString());
               }
               cons.Close();
               return count1;
           }

วันพุธที่ 16 ตุลาคม พ.ศ. 2556

Method Query Not Return MS Access (Access)

Method สำหรับ Query ได้แบ่งออกเป็น 2 แบบ คือ

1.รับค่าเป็นตัวแปร ชนิด String แล้วนำไป Query ข้อมูล

        OleDbConnection cons;
                public void querydb(String issql) //รับค่าเป็นคำสั่ง SQL ชนิด String
                {
                    this.cons.Open();
                    OleDbCommand cmd = this.cons.CreateCommand();
                    cmd.CommandText = issql;
                    cmd.ExecuteReader();
                    this.cons.Close();
                }

____________________________

2. รับค่าเป็นตัวแปร ชนิด OleDbCommand แล้วนำ ไป Query
                     Public void insert_data()
                    {
                             ConnectDB condb = new ConnectDB();
                             String sql = "insert into employee values(?,?,?,?,?,?,?,?,?,?)"; 
                          
                             OleDbCommand CMD = new OleDbCommand(sql, condb .reConnect()); // เรียกหาตัวแปล Con
                             CMD.Parameters.Add(new OleDbParameter("emp_id",OleDbType.VarChar)).Value = txtCode.Text;
                             CMD.Parameters.Add(new OleDbParameter("first_name", OleDbType.VarChar)).Value = txtfirstname.Text;
                             CMD.Parameters.Add(new OleDbParameter("last_name", OleDbType.VarChar)).Value = txtlastname.Text;
                             CMD.Parameters.Add(new OleDbParameter("sex", OleDbType.VarChar)).Value = txtsex;
                             CMD.Parameters.Add(new OleDbParameter("id_card", OleDbType.VarChar)).Value = txtidcard.Text;
                             CMD.Parameters.Add(new OleDbParameter("birth_day", OleDbType.VarChar)).Value = txtbirthday.Text;
                             CMD.Parameters.Add(new OleDbParameter("date_in", OleDbType.VarChar)).Value = txtwork.Text;
                             CMD.Parameters.Add(new OleDbParameter("address1", OleDbType.VarChar)).Value = txtadd1.Text;
                             CMD.Parameters.Add(new OleDbParameter("address2", OleDbType.VarChar)).Value = txtadd2.Text;
                             CMD.Parameters.Add(new OleDbParameter("company_id", OleDbType.VarChar)).Value = chkCompany();

                             condb .querydb(CMD);
                   }

______________   // Class ConnectDB

   
                     OleDbConnection cons;
                            public OleDbConnection reConnect()
                            {
                                return this.cons;
                            }

                            public void querydb(OleDbCommand cmd)

                            {
                                cons.Open();
                                cmd.ExecuteReader();
                                cons.Close();

                            }

                    

Method Connect Database MS Access (Access)

Method สำหรับ เชื่อมต่อ ฐานข้อมูล ประเภท Microsoft Access


               OleDbConnection cons;
               public Isfunction()
               {
               //  string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Directory.GetCurrentDirectory() + "\\npt_health.accdb;Persist Security Info=False;"; //File MDB
               //  string connect = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + Directory.GetCurrentDirectory() + "\\npt_health.mdb;Persist Security Info=False;"; // File ACCDB
                   String connect = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=..\\..\\npt_health.mdb;Persist Security Info=False;";
                   this.cons = new OleDbConnection(connect);
        }

//-------------------


** หาก เชื่อมต่อฐานข้อมูล Access ไม่ได้ เนื่องจากใช้  Windows 64 bit 
ให้ไปตั้งค่าที่ Project > Properties > แก้ให้เป็น x86 ตามรูป 

วันอังคารที่ 15 ตุลาคม พ.ศ. 2556

How to Print Report by Crystal Reports (C#) ตอนที่ 4 Insert Picture , Parameter Report , Set Details full Page

How to Print Report by Crystal Reports (C#)  ตอนที่ 4 Insert Picture , Parameter Report , Set Details full Page

1.Insert Picture การเพิ่ม รูปภาพลงใน Report
     

      สร้าง Table ใน DataSet สร้าง Field มา 1 Field มารองรับ ข้อมูลรูปภาพ 
      โดยใช้ DataType = System.Byte[]
  
      จากนั้นเขียน คำสั่งในการเพิ่ม รูปภาพ ลงใน Field ที่สร้างขึ้นมารองรับ

        public DataSet addPic(DataSet DS,String Patch)
        {
            DataRow tempRow = DS.Tables["Emp_pic"].NewRow(); // สร้าง บรรทัดใหม่ ขึ้นมา โดยใช้ DataRow
            tempRow["Emp_picture"] = mappicture("W:\\" + Patch + ".bmp"); // เพิ่มรูปภาพตาม Patch ลงใน DataRow ที่สร้าง
            DS.Tables["Emp_pic"].Rows.Add(tempRow);  // เพิ่ม รูปภาพลงใน DataSet ที่สร้างไว้
            return DS;
        }

        public byte[] mappicture(String Patch)
        {
            FileStream fiStream = new FileStream(Patch, FileMode.Open, FileAccess.Read); 
            BinaryReader binReader = new BinaryReader(fiStream);
            byte[] pic = { };
            pic = binReader.ReadBytes((int)fiStream.Length);
            return (pic);
        }

_____________________________________________________________________________

2.การสร้าง Parameter ใน Report เพื่อรับค่า จากโปรแกรม

ใน Report สามารถสร้าง Parameter สำหรับ รับค่าจากโปรแกรมแสดงที่ Report ได้ โดยสร้างที่ Parameter fields 
การส่งค่า 
          ReportDocument rpt = new ReportDocument();
          rpt.Load(Report);
          rpt.SetParameterValue("isYear", this.is_Year); // เพิ่มค่า ลง Parameter


_______________________________________________

3.Set Details Full Page 

          สำหรับแก้ไขปัญหา Detail ไม่เต็มหน้ากระดาษ มีพื้นที่ว่าง  Method ต่อไปนี้ จะเป็นการ ตรวจสอบและเพิ่มข้อมูลให้ครบ 1 หน้ากระดาษพอดี  โดยข้อมูลที่เพิ่มมาจะไม่ได้แสดงใน Report แต่จะทำให้ตีกรอบตาราง ให้สวยงาม

          โดยใช้วิธี  1 หน้ากระดาษ มี Details ได้มากสุด 20   หาก Report ที่แสดงออกมา มี 14 ก็ใช้วิธี 20 - 14 = 6 คือจำนวนของ ช่องเปล่าที่ต้องแสดงออกมาให้ครบ พอดี 1 หน้ากระดาษ โดยเพิ่มข้อมูล ลงไป ให้ครบ แต่ เป็นข้อมูลที่ไม่แสดงที่ Report แต่จะทำให้ตีกรอบข้อมูล

Code
    public DataSet chkdataset(DataSet DS)
        {
            int freerows = 20 - ((DS.Tables["ITR_Topic_db"].Rows.Count) % 20); // หาจำนวนที่เหลือเพื่อให้ ครบ 1 หน้ากระดาษ
            if (((DS.Tables["ITR_Topic_db"].Rows.Count) % 20) != 0)
            {
                for (int i = 0; i < freerows; i++)
                {
                    DataRow tempRow = DS.Tables["ITR_Topic_db"].NewRow();
                    tempRow["Topic_code"] = "temp" + i;                      
                    DS.Tables["ITR_Topic_db"].Rows.Add(tempRow);              //เพิ่มข้อมูล ให้ตรบ 20 บรรทัด  
                }
            }
            return DS;
        }


How to Print Report by Crystal Reports (C#) ตอนที่ 3 Query Database to DataSet And Display Report

How to Print Report by Crystal Reports (C#) ตอนที่ 3 Query Database to DataSet And Display Report

1. Method สำหรับ นำคำสั่ง SQL ไป Query ข้อมูล ออกมาในรูปแบบของ DataSet

        public DataSet First(String Emp_code, String isYear)
        {
            DataSet2 sDs = new DataSet2(); // DataSet ทีสร้าง ไว้ก่อนหน้านี้ 
            String strSQl = "select e.Emp_code,e.Prename_th,e.Firstname_th,e.Lastname_th,"
                             + " e.Prename_eng,e.Firstname_eng,e.Lastname_eng,e.Grade_name,"
                             + " d.Dept_name,e.Emp_date"
                             + " from ITR_EMP_db e left join ITR_Dept_db d"
                             + " on e.Dept = d.Dept_no"
                             + "  where e.act <> 'D' and e.Emp_code = '" + Emp_code.Trim() + "'";
            //strSQl สำหรับ ดึงหัวข้อ เพื่อแสดงที่ Page Header มี 1 ค่า 

             String strSQL2 = "Select t.Topic_code,t.Pln_from,t.Pln_to,t.Topic_name,t.Term,"
                              + "t.Trainner1,t.Approve,d.Result,t.Unit from ITR_Details d"
                              + " left join ITR_Topic_db t on d.Topic_code = t.Topic_code"
                              + " where t.act <> 'D' and d.act <> 'D' and d.Emp_code = '" + Emp_code+ "'"
                              + " and t.pln_from like '%" + isYear.Trim() + "'"
                             + " and (Select COUNT(*) from ITR_Details s"
                             + " where s.Act <> 'D' and s.Topic_code = t.Topic_code and s.Result = '-') = 0 "
                             
                              + " order by (SUBSTRING(t.Pln_from,4,2)+SUBSTRING(t.Pln_from,1,2))";
            //StrSQL สำหรับ ดึงค่า Details ออกมาแสดง ในส่วนของ Details มีมากกว่า 1 ค่า      
           return Query_Report(strSQl, strSQL2, "ITR_EMP_db", "ITR_Topic_db", sDs); // Return เป็น DataSet
        }

__________________________________________________

2. Method สำหรับ Query ออกมา แล้ว Return ออก ในรูปแบบ DataSet ที่สร้างไว้ใน DataSet2

    public DataSet2 Query_Report(String isSQL, String isSQL2, String Database, String Database2, DataSet2 sds)
        {
          try{
            this.objConn.Open();
       // 1
            this.objCmd = new SqlCommand(isSQL, objConn);
            SqlDataAdapter sadpter = new SqlDataAdapter(this.objCmd);
            sds.Clear();
            sadpter.Fill(sds, Database);
      //  2
            this.objCmd = new SqlCommand(isSQL2, objConn);
            sadpter = new SqlDataAdapter(this.objCmd);
            sadpter.Fill(sds, Database2);

            this.objConn.Close();
            return sds;
        }
        catch (InvalidOperationException XcpInvOp)
            {
                System.Windows.Forms.MessageBox.Show(XcpInvOp.ToString());
                  return null;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
                   return null;
            }
        }

_______________________________________________

3.Method สำหรับ จัดการข้อมูล และ  แสดง Report 

using System.IO;  //เอาไว้หาข้อมูลปัจจุบัน Directory.GetCurrentDirectory()
using CrystalDecisions.CrystalReports.Engine; // เอาไว้เรียก Report ReportDocument 

 public void First()
        {
                Result_view_con tvc = new Result_view_con();
                DataSet Data2 = tvc.First(this.Emp_code, this.is_Year);  // สำหรับ Query ข้อมูล Return เป็น DataSet
         
                Data2 = addPic(Data2, this.Emp_code); // เพิ่มรูปภาพ
                Data2 = chkdataset(Data2); // ตรวจสอบข้อมูลที่แสดงออก Details
                ReportDocument rpt = new ReportDocument();
       
            //*******************************************************************************************   Connect report c# 
                try
                {
                    String Report = Directory.GetCurrentDirectory() + "\\Report\\QR-AD-002.rpt";  // สำหรับ เรียกหา Report โดย Directory.GetCurrentDirectory() ดึงที่อยู่ปัจจุบัน
                    rpt.Load(Report);
                }
                catch (Exception)
                {
                    rpt.Load("..\\..\\QR-AD-002.rpt");
                }
                //*******************************************************************************************   Connect report c# 
   
                rpt.Database.Tables[0].SetDataSource(Data2.Tables[0]); // เพิ่ม ตารางใน DataSet ที่สร้าง ตารางที่ 1
                rpt.Database.Tables[1].SetDataSource(Data2.Tables[1]); // ตารางใน DataSet ที่สร้าง ตารางที่ 2
                rpt.Database.Tables[2].SetDataSource(Data2.Tables[2]); // ตารางใน DataSet ที่สร้าง ตารางที่ 3
                rpt.SetParameterValue("isYear", this.is_Year); // เพิ่มค่าในตัวแปร isYear ใน Report

                this.Result_view_form.ReportSource = rpt;
                this.Result_view_form.DisplayGroupTree = false;  
                this.Result_view_form.Refresh();

        }

____________________________________________________________________

How to Print Report by crystal reports (C#) ตอนที่ 2 Create Report,Connect DataSet,Create Formula

1.How to Print Report by crystal reports (C#)  ตอนที่ 2  Create Report and Connect DataSet

1.Connect Report With DataSet
         -
       - เมื่อสร้าง Report ขึ้นมา Right Click ที่ Database Fields >  เลือก ADO .Net Dataset
       - จะมีรายการ DataSet ที่สร้างไว้ ในตอนแรก จากนั้น Click Add ไป Selected Tables กด ปุ่ม OK

______________________________________________________

2.สร้างข้อความธรรมดา โดยการ Left Click > Insert > Text Object และดึง Fields ที่เลือกไว้ในตอนแรกใน Fields Explorer มาใน Report โดยเลือก ข้อมูลหลักที่มี 1 ข้อมูล ไว้ใน Page Header ส่วนข้อมูลที่เป็น Details มากกว่า 1 ค่าไว้ใน Details 


___________________________________________________

3.Create Formula ไว้สำหรับ การตรวจสอบและแสดงข้อมูล ที่ได้จาก DataSet เช่น เมื่อข้อมูล ใน DataSet ไม่มีค่า อะไร ให้แสดง "-" เป็นต้น

           ตัวอย่าง 
          3.1      การสร้าง Formula สำหรับ แสดงหมายเลขหน้ากระดาษ
                    โดยเลือก Function > Page Number > เมื่อสร้างเสร็จก็ ดึงไปแสดงที่ Report เหมือน Fields

          3.2     การนำข้อมูลที่ได้จาก DataSet มาตรวจสอบ เพื่อแสดงค่า
                    ในตัวอย่าง ใน DataSet2 > ตาราง ITR_Topic_db > Field Pln_from
                     มีค่าคือ (15/10/2013) เมื่อแสดง Report เมื่อผ่าน Formula จะแสดงเป็น 15 Oct 2013
                     โดยใช้ คำสั่ง Mid คือ SubString ตัดคำ มาช่วยในการ แยก วัน เดือน ปี

วันจันทร์ที่ 14 ตุลาคม พ.ศ. 2556

How to Print Report by crystal reports (C#) ตอนที่ 1 Create DataSet

1.How to Print Report by crystal reports ตอนที่ 1 สร้าง DataSet รองรับ

1.สร้าง DataSet ขึ้นมา เพื่อรับข้อมูล ก่อนออก Report  สามารถสร้างโดยใช้ คำสั่ง หรือว่า สร้างโดยใช้ Tool ก็ได้



2. สร้าง DataSet โดยสร้าง field ตามที่ จะออก Report โดยใน DataSet มีได้หลาย DataTable

3.โครงสร้างออก Report







Method Export to Excel (C#)

1. Method Export Data To Excel File  

 อย่างแรก ต้อง Add Reference ของ Office


  private void Export_Click(object sender, EventArgs e)
        {
            string[] Headertxt = new string[12] { "รหัสพนักงาน", "คำนำหน้า", "ชื่อ", "สกุล", "คำนำหน้า", "ชื่ออังกฤษ", "สกุลอังกฤษ", "ระดับ", "รายละเอียดระดับ", "วันเข้างาน", "เลขที่บัตรประชาชน", "แผนก" };
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
            Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
            Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
            app.Visible = true;
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets["Sheet1"];
            worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.ActiveSheet;
            worksheet.Cells[1, 1] = "รายชื่อพนักงาน";
                        for (int i = 0; i < Headertxt.Length - 1; i++)
                        {
                                        worksheet.Cells[2, i + 1] = Headertxt[i];
                        }
            int c = 3;
            String Stock = null;
                        for (int i = 0; i < Topic_table.Rows.Count; i++)
                        {
                            if (i == 0)
                            {
                                            Stock = "'" + Topic_table.Rows[i].Cells[0].Value.ToString() + "',";
                            }
                            else
                            {
                                            Stock = Stock + "'" + Topic_table.Rows[i].Cells[0].Value.ToString() + "',";
                            }
                        }
            Stock = (Stock.Substring(0, Stock.Length - 1));
            String StrSQL = "select Emp_code,Prename_th,Firstname_th,Lastname_th,"
                             + " Prename_eng,Firstname_eng,Lastname_eng,Grade,"
                             + " Grade_name,Emp_date,Id_card,Dept_name"
                             + " from ITR_EMP_db left join ITR_Dept_db"
                             + " on ITR_EMP_db.Dept = ITR_Dept_db.Dept_no"
                             + " where ITR_EMP_db.act <> 'D' and Emp_code in (" + Stock + ")";
            DataSet DS1 = IR_con.Query_All(StrSQL, "ITR_Emp_db");

            for (int r1 = 0; r1 < DS1.Tables[0].Rows.Count; r1++)
            {
                for (int c1 = 0; c1 < DS1.Tables[0].Columns.Count - 1; c1++)
                {
                    worksheet.Cells[c, c1 + 1] = "'" + DS1.Tables[0].Rows[r1][c1].ToString();
                }
                c++;
            }
        }

Method Get Computer Name (C#)

Method Return Computer Name

            private String Get_Computername()
            {
                        return  System.Environment.MachineName; // Get Computer Name
            }

Method Check Between Day 2 Values , Split Date(DD/MM/YY) and Change B.E.(พ.ศ.) to A.D.(ค.ศ.)

1. Method Check Between Day 2 Values หาค่าระหว่างวันที่ 2 วันที่ 
            public String checkDate(String date1, String date2)
                   {
                       try
                       {
                           if (Convert.ToDateTime(date1) >= Convert.ToDateTime(date2))
                           {
                               TimeSpan ts = Convert.ToDateTime(date1) - Convert.ToDateTime(date2);
                               return ts.Days.ToString();
                           }
                           else
                           {
                               return "no";
                           }
                       }
                       catch (Exception)
                       {
                           return "error";
                       }
                   }

____________________________________________________

2. Method Split Date ( DD/MM/YY ) return String Array แยก วัน เดือน ปี เป็น Array
         //INPUT DD/MM/YY
                public string[] splitdate(String isDay1)
                {
                    string[] Date1 = isDay1.Split('/');
                          return Date1;
                }

____________________________________________________

3.Method Change B.E. to A.D. ( พ.ศ. เป็น ค.ศ.)  

ถ้าคอมพิวเตอร์ ตั้งค่าวันที่เป็น พ.ศ. วันที่ DateTime.Now จะได้ เป็น พ.ศ.
สามารถทำให้เป็น ค.ศ.โดยวิธีดังนี้

using System.Globalization; private CultureInfo german = new CultureInfo("en-US");
TextBox1.Text = DateTime.Now.ToString("dd/MM/yyyy", german);




Method Check input Data in Textbox only numeric(0-9) and dot(.) (C#)

ทำการตรวจสอบ การ Input ค่าลงบน Textbox ต้องเป็น ตัวเลข หรือ . เท่านั้น โดยดักโดนใช้ ACSSII
  
1.ดัก Event   
        private void Textbox1_Keyprass(object sender, KeyPressEventArgs e)
        {
            e.Handled = CheckKeycode(e.KeyChar);
        }


2.Check Input
 public bool CheckKeycode(char CurrentChar)
        {
            int cInt = Convert.ToInt32(CurrentChar);
            if ((int)CurrentChar >= 48 && (int)CurrentChar <= 57 || cInt == 8) // ตรวจตัวเลข
            {
                return false;
            }
            else
            {
                if ((int)CurrentChar == 46) // ตรวจจุด
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }

Method Click DataGridView Display to Textbox (C#)


เมื่อมีการ Click ที่ DataGridview จะแสดงข้อมูล บน Textbox
      
private void DataGridview _CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

            if (e.RowIndex < 0 || e.ColumnIndex < 0)
                return;
           Textbox.Text =  DataGridview.Rows[e.RowIndex].Cells[0].Value.ToString().Trim();
           Textbox1.Text = DataGridview.Rows[e.RowIndex].Cells[1].Value.ToString().Trim();
           Textbox2.Text = DataGridview.Rows[e.RowIndex].Cells[2].Value.ToString().Trim();
           Textbox3.Text = DataGridview.Rows[e.RowIndex].Cells[3].Value.ToString().Trim();
           Textbox4.Text = DataGridview.Rows[e.RowIndex].Cells[4].Value.ToString().Trim();          
           Textbox5.Text = DataGridview.Rows[e.RowIndex].Cells[5].Value.ToString().Trim();

      }

วันพุธที่ 9 ตุลาคม พ.ศ. 2556

Method Display Data In DataGridView (C#)

เป็นการแสดงข้อมูลน ตาราง DataGridView แบบที่ 1 For Loop แสดง

แบบที่ 1. เป็นการแสดง ออก DataGridView ทีละ บรรทัด DataRow 

โดยประกอบด้วย
   1.Method สำหรับ แสดงข้อมูลออกตาราง DataGridView โดยมี ตรวจสอบว่า มีข้อมูลในอีกตารางหรือไม่ ถ้าไม่มี ให้ทำการ แสดงข้อมูลออกตารางเป็นสีแดง ถ้ามี ให้แสดง เป็นสีดำ

        public void showTable(String Dept_no)
        {
            String isSQL = "Select t.Topic_code,t.Topic_name,d.Dept_name,t.pln_from,t.pln_to"
                            + " from ITR_Topic_db t left join ITR_Dept_db d "
                            + " on t.Dept = d.Dept_no where Dept = '" + Dept_no + "' and T.act <> 'D'  and ( "
                            + "(Select COUNT(*) from ITR_Details d"
                            + " where d.Topic_code = t.Topic_code and t.act <> 'D' and d.act <> 'D' and Result = '-') > 0 "
                            + " or (Select Count(*) from ITR_Details d"
                            + " where d.Topic_code = t.Topic_code and d.act <> 'D' and d.Result  in('-','1','2','3','4','5','6','7')) = 0 )"
                            + " Order by t.Topic_code";

          ConnectDatabase ConDb = new ConnectDatabase();
          DataSet DataTable1 = ConDb.Query_All(isSQL, "ITR_Topic_db");

            int i = 0;
            DataGridView.Rows.Clear();
            foreach (DataRow theRow in DataTable1.Tables["ITR_Topic_db"].Rows)
            {
                this.DataGridView.Rows.Add();
                if (chekResult(theRow[0].ToString()).Equals("0"))
                {
                    this.DataGridView.Rows[i].Cells[0].Style.ForeColor = Color.Red;
                    this.DataGridView.Rows[i].Cells[0].Style.SelectionForeColor = Color.Red;
                }
                else
                {
                    this.DataGridView.Rows[i].Cells[0].Style.ForeColor = Color.Black;
                    this.DataGridView.Rows[i].Cells[0].Style.SelectionForeColor = Color.White;
                }
                this.DataGridView.Rows[i].Cells[0].Value = theRow[0].ToString();
                this.DataGridView.Rows[i].Cells[1].Value = theRow[1].ToString();
                this.DataGridView.Rows[i].Cells[2].Value = theRow[2].ToString();
                this.DataGridView.Rows[i].Cells[3].Value = theRow[3].ToString();      
                this.DataGridView.Rows[i].Cells[4].Value = theRow[4].ToString();
                i++;
            }
        }
__________________________________________________________________________
                    1.2. Method สำหรับตัวตรวจสอบ ว่ามีข้อมูลในอีก ตาราง หรือไม่
                                         ConnectDatabase ConDb = new ConnectDatabase();
                                         private String chekResult(String topic_code)
                                                {
                                                            return ConDb.Query_one("Select count(*) from ITR_details where Act <> 'D' and                                                             Topic_code = '" + topic_code + "'", "ITR_details").ToString();
                                                  }                    

___________________________________________________________________

2. แบบที่ 2 ใช้ Method  DataSource ของ DatagridView ในการแสดง 

                 ConnectDatabase ConDb = new ConnectDatabase();
                       public void showTable(String isSQL, String DB)
                             {
                                 DataSet DataTable1 = ConDb .Query_All(isSQL, DB);

                                 DataGridView.DataSource = null;

                                 this.table_listemp.DataSource = DataTable1.Tables[0]; ;

                                 DataGridView.Columns[0].Width = 30;
                                 DataGridView.Columns[1].Width = 100;
                                 DataGridView.Columns[2].Width = 100;
                                 DataGridView.Columns[3].Width = 300;
                                 DataGridView.Columns[0].HeaderText = "Check";
                                 DataGridView.Columns[1].HeaderText = "ชื่อ";
                                 DataGridView.Columns[2].HeaderText = "นามสกุล";
                                 DataGridView.Columns[3].HeaderText = "Grade Name";

                    }

Method Query Database List Return (C#)

แบ่งออกเป็น 2 แบบ
Return เป็น List<String> เหมาะสำหรับ Combobox เป็นต้น
1. รับตัวแปร เป้น String คำสั่ง SQL เพื่อทำการ Query return List<String>

        public List<String> Query(String isSQL)
        {
            try
            {
                this.objConn.Open();

                List<String> dp = new List<String>();
                this.objCmd = new SqlCommand(isSQL, this.objConn);
                SqlDataReader reader = objCmd.ExecuteReader();
                while (reader.Read())
                {
                    dp.Add(reader[1].ToString());
                }
                this.objConn.Close();
                return dp;
            }
            catch (InvalidOperationException XcpInvOp)
            {
                System.Windows.Forms.MessageBox.Show(XcpInvOp.ToString());
                  return null;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
                   return null;
            }
        }

__________________________________________________________________

2. รับตัวแปรเป็น Command แล้ว ทำการ Query เป็น List<String>
       public List<String> Query(SqlCommand cmd)
        {
            try
            {
                this.objConn.Open();

                List<String> dp = new List<String>();
                this.objCmd = cmd;
                SqlDataReader reader = objCmd.ExecuteReader();
                while (reader.Read())
                {
                    dp.Add(reader[1].ToString());
                }
                this.objConn.Close();
                return dp;
            }
            catch (InvalidOperationException XcpInvOp)
            {
                System.Windows.Forms.MessageBox.Show(XcpInvOp.ToString());
                  return null;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
                   return null;
            }
        }

     

Method Query Database Dataset Return (C#)

แบ่งออกเป็น 2 แบบ
1. Send Parameter String SQL and Database Name Return DataSet
 public DataSet Query_All(String isSQL, String Database)
        {
       try{
            this.objConn.Open();
            DataSet ds = new DataSet();

            this.objCmd = new SqlCommand(isSQL, objConn);

            SqlDataAdapter sadpter = new SqlDataAdapter(this.objCmd);
            ds.Clear();
            sadpter.Fill(ds, Database);

            this.objConn.Close();
            return ds;
                   }
            catch (InvalidOperationException XcpInvOp)
            {
                System.Windows.Forms.MessageBox.Show(XcpInvOp.ToString());
                  return null;
            }
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.ToString());
                   return null;
}
        }

_________________________________________________________________

2. Send Parameter Command and Return DataSet
        public DataSet Query_All(SqlCommand cmd,String DB)
                {
                    try
                    {
                        this.objConn.Open();
                        DataSet ds = new DataSet();

                        this.objCmd = cmd;
                        SqlDataAdapter sadpter = new SqlDataAdapter(this.objCmd);

                        ds.Clear();
                        sadpter.Fill(ds, DB);
                        this.objConn.Close();
                        return ds;
                    }
                    catch (InvalidOperationException XcpInvOp)
                    {
                        System.Windows.Forms.MessageBox.Show(XcpInvOp.ToString());
                          return null;
                    }
                    catch (Exception e)
                    {
                        System.Windows.Forms.MessageBox.Show(e.ToString());
                           return null;
                    }

                }