Archive

Archive for September 30, 2008

The MessageBox Class

September 30, 2008 1 comment

เนื่องจาก คราวที่แล้วได้ทิ้งไว้ว่า ในการทำ validation นั้นจะต้องมีการแสดง Message หรือ ข้อความแจ้งต่อผู้ใช้งานถึงข้อผิดพลาด และให้ใส่ข้อมูลให้ถูกต้อง การแสดง Message เหล่านี้มีการแสดง ได้หลายวิธีคือ การใช้ MessageBox Class  การใช้ ErrorProvider หรือ การใช้ StatusStrip (status bar) ในบทความนี้เราจะพูดถึงการใช้ MessageBox Class

เรื่องของ MessageBox Class นั้น การใช้งาน ใช้แสดงข้อความโต้ตอบกับผู้ใช้ งานเป็น Windows Message พร้อมทั้งแสดง icon และ ปุ่มที่เราสามารถที่จะกำหนด ได้ตามความต้องการ ในการแสดง MessageBox นั้นเราจะเรียก method ชื่อว่า show()

Show() method นั้นเป็น static method โดยจะรับ arguments 4 ตัวด้วยกันคือ message, title name, buttons, icons การใช้งานก็เป็น ดังตัวอย่าง code นี้นะครับ

private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(“The entered data is not valid. Please enter valid data”,
“Data Entry Error”, MessageBoxButton.OK, MessageBoxIcon.Error);
}

จาก code ดังกล่าว จะแสดง MessageBox ดังนี้นะครับ

จาก code ด้านบนเราจะเห็นว่า parameter แรก คือ “The entered data is not valid. Please enter valid data” นั้นแสดงเป็น message ใน MessageBox  parameter ตัวที่สอง คือ “Data Entry Error” ก็คือ ส่วนที่เป็น Title ของ MessageBox  parameter ตัวที่สาม คือ MessageBoxButton.OK เป็น enum type นะครับ ใช้สำหรับ กำหนดจำนวน และชนิดของปุ่มที่จะใช้แสดง  parameter ตัวสุดท้าย MessageBoxIcon.Error ใช้กำหนด รูป Icon ที่แสดง คู่กับ Message ที่เรากำหนด  ถึงตรงนี้คงพอจะเข้าใจแล้วนะครับ ว่าจะใช้งานมันได้อย่างไร

ส่วนตารางด้านล่างเป็น รายละเอียด ของ MessageBoxButton และ MessageBoxIcon Enumeration

Option Description
AbortRetryIgnore แสดง ปุ่ม Abort, Retry, and Ignore
OK แสดง ปุ่ม Ok (default)
OKCancel แสดง ปุ่ม Ok , Cancel
RetryCancel แสดงปุ่ม Retry, Cancel
YesNoCancel แสดงปุ่ม Yes No Cancel
YesNo แสดงปุ่ม Yes, No

Option Description
Asterisk
Error
Exclamation
Hand
Information
None
Question
Stop
Warning

ครับ จากข้อมูลที่ ได้กล่าวมานั้นคงจะได้ แนวคิดในการ ใช้งานแล้วนะครับ

มาดูอีกตัวอย่างการใช้งานนะครับ เนื่องจาก MessageBox ไม่ได้ใช้ในการแสดง ข้อความอย่างเดียวนะครับ มันสามารถที่จะตอบรับ การตัดสินใจของ ผู้ใช้งานได้ด้วย นั่นก็คือ DialogResult นั่นเ้องครับ   DialogResult เป็น enumeration ที่มีค่าต่าง ๆ ที่ Dialog จะ return หลังจากที่ ผู้ใช้งาน click ปุ่มใด ปุ่มหนึ่ง  OK หรือ Cancel ดูจากตัวอย่างก็แล้วกันนะครับ

DialogResult res =  MessageBox.Show(“Confirm Delete data.”,
“Deletion confirm”, MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
if (res == DialogResult.OK)
{
// Perform some task
}

จาก code จะเห็น ว่า MessageBox.Show()  จะ return ค่าใดค่าหนึ่งออกมาขึ้นอยู่ว่าผู้ใช้จะคลิกปุ่มใด  เราใช้ ตัวแปร  DialogResult รับค่าแล้วนำไป ตรวจสอบใน if( res == DialogResult.OK ) ว่าผู้ใช้ click ปุ่ม Ok หรือไม่ ถ้าใช้ ก็ทำงานใดงานหนึ่ง ที่เราต้องการ หรือ ถ้าผู้ใช้ click  Cancel ก็ผ่านไปเลย ไม่ต้องสนใจ อย่างนี้เป็นตันนะครับ สำหรับ เรื่องของการใช้ MessageBox ก็มีอันจบลง แค่นี้นะครับ

Categories: C# .NET, Windows Forms