当前位置:编程学习 > C#/ASP.NET >>

asp.net编程的问题27

Click和Command这两个事件有什么不同????

答案:
当按钮被包含该按钮的表单被提交,并且发出Click和Command事件。Click和Command事件之间的差别在于附加信息:CommandName和CommandArgs被传递给Command事件。在有多个button出现的时候(大多数时候是几个button出现在一个容器控件里面),就可以通过这些参数判断来做什么操作。

你好:)

Click事件只针对具体的某个Button。

但是Command事件可以针对所有的Button,通过CommandName来区分究竟是哪个Button被点击了。你可以设置CommandName以便在Command事件中获取并且区分究竟是哪个Button被触发了。

 

<%@ Page Language="C#" AutoEventWireup="True" %>

<html>
<head>

<script runat="server">

void CommandBtn_Click(Object sender, CommandEventArgs e)
{

switch(e.CommandName)
{

case "Sort":

// Call the method to sort the list.
Sort_List((String)e.CommandArgument);
break;

case "Submit":

// Display a message for the Submit button being clicked.
Message.Text = "You clicked the Submit button";

// Test whether the command argument is an empty string ("").
if((String)e.CommandArgument == "")
{
// End the message.
Message.Text += ".";
}
else
{
// Display an error message for the command argument.
Message.Text += ", however the command argument is not recogized.";
}
break;

default:

// The command name is not recognized. Display an error message.
Message.Text = "Command name not recogized.";
break;

}

}

void Sort_List(string commandArgument)
{

switch(commandArgument)
{

case "Ascending":

// Insert code to sort the list in ascending order here.
Message.Text = "You clicked the Sort Ascending button.";
break;

case "Descending":

// Insert code to sort the list in descending order here.
Message.Text = "You clicked the Sort Descending button.";
break;

default:

// The command argument is not recognized. Display an error message.
Message.Text = "Command argument not recogized.";
break;

}

}

</script>

</head>

<body>

<form runat="server">

<h3>Button CommandName Example</h3>

Click on one of the command buttons.

<br><br>

<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>

&nbsp;

<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>

<br><br>

<asp:Button id="Button3"
Text="Submit"
CommandName="Submit"
OnCommand="CommandBtn_Click"
runat="server"/>

&nbsp;

<asp:Button id="Button4"
Text="Unknown Command Name"
CommandName="UnknownName"
CommandArgument="UnknownArgument"
OnCommand="CommandBtn_Click"
runat="server"/>

&nbsp;

<asp:Button id="Button5"
Text="Submit Unknown Command Argument"
CommandName="Submit"
CommandArgument="UnknownArgument"
OnCommand="CommandBtn_Click"
runat="server"/>

<br><br>

<asp:Label id="Message" runat="server"/>

</form>

</body>
</html>

上一个:ASP.NET编程的问题11
下一个:ASP.NET编程的问题05

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,