방법: Button 웹 서버 컨트롤 이벤트에 응답
업데이트: 2007년 11월
Button, LinkButton 또는 ImageButton 웹 서버 컨트롤을 클릭하면 현재 페이지가 서버에 전송되어 처리됩니다.
단추 이벤트에 응답하려면
다음 이벤트 중 하나에 대한 이벤트 처리기를 만듭니다.
페이지의 Page_Load 이벤트. 단추는 페이지를 항상 서버로 게시하기 때문에 이 메서드는 항상 실행됩니다. 어떤 단추가 클릭되었는지가 아니라 폼이 전송되었는지 여부만 확인하려는 경우 Page_Load 이벤트를 사용합니다.
단추의 Click 이벤트. 어떤 단추가 클릭되었는지 확인하려는 경우 이 이벤트에 대한 이벤트 처리기를 작성합니다.
참고: ImageButton 컨트롤을 사용하고 있고 사용자가 클릭한 지점의 x, y 좌표를 확인하려는 경우 이 이벤트에 대한 이벤트 처리기를 만들어야 합니다. 자세한 내용은 방법: ImageButton 웹 서버 컨트롤에서 좌표 확인을 참조하십시오.
다음 예제에서는 사용자가 Button 웹 서버 컨트롤을 클릭할 때의 응답 방법을 보여 줍니다. 메서드는 Label 웹 서버 컨트롤에 메시지를 표시합니다.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Label1.Text="You clicked a button" End Sub
public void Button1_Click (object sender, System.EventArgs e) { Label1.Text="You clicked a button."; }
다음 예제에서는 Page_Load 이벤트 처리기에서의 단추 클릭에 대한 응답 방법을 보여 줍니다. 이 메서드는 페이지의 IsPostBack 속성을 테스트하여 페이지가 처음으로 처리된 것인지, 페이지가 단추 클릭에 의해 전송되었는지 여부를 확인합니다.
Private Sub Page_Load(ByVal Sender As System.Object, ByVal e _ As System.EventArgs) Handles MyBase.Load If Not IsPostback Then ' This is called the first time the page has loaded. ' The user will not have been able to click any buttons yet. Else ' This is called if the form has been posted back, possibly ' by a button click. Me.Label1.Text = "You clicked a button." End If End Sub
private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { // Evals true first time browser hits the page. } else { // This is called if the form has been posted back, possibly // by a button click. this.Label1.Text = "You clicked a button."; } }
다음 예제는 네 가지 기능을 가진 간단한 정수 계산기를 보여 줍니다. 모든 단추(덧셈, 뺄셈, 곱셈 및 나눗셈)를 동일한 메서드에 바인딩하면 한 위치에서 모든 계산을 처리할 수 있고 코드를 반복하지 않아도 됩니다. Visual Basic의 경우 AddHandler 메서드를 사용하고 C#의 경우 += 연산자를 사용하여 단추를 Calculate 메서드에 바인딩합니다. 정수 값만 입력 받으려면 Calculate 메서드에 오류 처리 코드를 추가하거나 Web Forms에서 사용할 수 있는 유효성 검사 컨트롤을 사용합니다.
' Set the CommandName property of the buttons to "Add", ' "Subtract", "Multiply", and "Divide". Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load AddHandler Me.btnAdd.Click, AddressOf Calculate AddHandler Me.btnSubtract.Click, AddressOf Calculate AddHandler Me.btnMultiply.Click, AddressOf Calculate AddHandler Me.btnDivide.Click, AddressOf Calculate End Sub Public Sub Calculate(ByVal sender As Object, ByVal e As System.EventArgs) Dim op1 As Integer = CType(Me.TextBox1.Text, Integer) Dim op2 As Integer = CType(Me.TextBox2.Text, Integer) Dim result As Integer Select Case CType(sender, Button).CommandName Case "Add" result = op1 + op2 Case "Subtract" result = op1 - op2 Case "Multiply" result = op1 * op2 Case "Divide" ' Divide two numbers and return an integer result. If op2 > 0 Then result = op1 \ op2 Else result = 0 End If Case Else ' Error handling code here. End Select Label1.Text = result.ToString() End Sub
// Set the CommandName property of the buttons to "Add", _ // "Subtract", "Multiply", and "Divide". protected void Page_Load(object sender, EventArgs e) { btnAdd.Click += new System.EventHandler(this.Calculate); btnSubtract.Click += new System.EventHandler(this.Calculate); btnMultiply.Click += new System.EventHandler(this.Calculate); btnDivide.Click += new System.EventHandler(this.Calculate); } protected void Calculate (object sender, System.EventArgs e) { int op1 = Convert.ToInt16(TextBox1.Text); int op2 = Convert.ToInt16(TextBox2.Text); int result = 0; switch(((Button)sender).CommandName) { case "Add" : result = op1 + op2; break; case "Subtract" : result = op1 - op2; break; case "Multiply" : result = op1 * op2; break; case "Divide" : // Integer division. if (op2 > 0) result = op1 / op2; else result = 0; break; default: // Error handling code here. break; } Label1.Text = result.ToString(); }