Repeater Control finding the object that raises the event
Inside repeater control He开发者_开发问答aderTemplate i have some LinkButtons and Checkbox I want to findout the object (Linkbutton or checkbox) that raises the event.
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
switch(e.CommandSource)
{
case LinkButton:some work here;
case CheckBox :some work here;
}
}
When i write such code i received error as
A switch expression or case label must be a bool,
char, string, integral, enum, or corresponding nullable type
How to achieve this?
As the error messages states you could use switch with bool, char, string, integral, enum or corresponding nullable type. In your case you want to compare types. This could be achieved with an if
statement:
if (e.CommandSource is LinkButton)
{
}
else if (e.CommandSource is CheckBox)
{
}
First, I pretty sure the checkbox won't ever fire the Repeater_ItemCommand event, as it is not a Button (or something that inheriets from Button) as only buttons create the ItemCommand event inside a Repeater. You can set the CheckBox's AutoPostBack property to true and handle it's OnClick event, though you'll have to be careful to be able to figure out which CheckBox fired the event b/c all the CheckBoxes will have the same event handler in your code behind files and they won't have some of the nice information inside the EventArgs that events raised by the Repeater will have.
In addition, checking the control type in the ItemCommand event handler seems both inefficent and limiting. As your code would break if there were ever mulltiple controls of the same type in the Repeater row that needed different processing. For controls that will actually raise the ItemCommand event, setting either the CommandName or the CommandArgument property of button will allow you to uniquely identify the control that raised the event, without taking the performance hit of the type check, plus it will be more maintainable.
Use this code within the ItemCommand event handler:
switch(e.CommandName)
{
case "LinkButtonCommandName1":
.......
break;
case "LinkButtonCommandName2":
.......
break;
}
精彩评论