I'm trying to access a button via the sender object inside a handler. However, I keep getting this exception:
Specified cast is not valid.
I know it's a simple issue but could someone help me see what I'm missing? It also doesn't have to specifically be the tag, I would just like to know which button was clicked.
This is the line where I get the exception:
var tag = ((UIButton)sender).Tag;
protected void Handle_FinishedPickingMedia (object sender, UIImagePickerMediaPickedEventArgs e)
{
try{
//determine what was selected, video or image
bool isImage = false;
switch(e.Info [UIImagePickerController.MediaType].ToString()) {
case "public.image":
Console.WriteLine("Image selected");
isImage = true;
break;
}
// if it was an image, get the other image info
if(isImage) {
// get the original image
UIImage originalImage = e.Info[UIImagePickerController.OriginalImage] as UIImage;
if(originalImage != null) {
// do something with the image
new Thread(new System.Threading.ThreadStart(() => {
Thread.Sleep(350);
BeginInvokeOnMainThread (() => {
var tag = ((UIButton)sender).Tag;
//UIButton senderButton = (UIButton)sender;
switch(tag)
{
case 0:
// do something here
break;
case 1:
// do something here
break;
});
})).Start();
}
}
// dismiss the picker
imagePicker.DismissModalViewController (true);
}catch(Exception ex)
{
ShowAlert ("Failed !", "Unable to select image", "");
Console.WriteLine(ex.Message + ex.StackTrace);
}
}
try something like this:
UIButton button = sender as UIButton;
var tag = button.tag;
also you can add some checks for the case when the "button" is null, eg. sender is not a UIButton
Based on Jason's suggestion above, the UIImagePickerController was the sender and not the buttons launching the picker. This is how I fixed the issue:
Created a global tag variable
int tag { get; set; }
Assigned the tag value inside each button's click handler. For instance:
button.TouchUpInside += (object sender, EventArgs e) => { tag = 0; // Do other stuff here };
The use the tag variable in the switch statement.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.