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

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;
            }
        }

     

ไม่มีความคิดเห็น:

แสดงความคิดเห็น