How to get image value of Datagridview Image Cell - vb.net

I have an datagridview with play image ImageColumn and if user click play icon then CellClick Event set "Stop" image from Resources.
Private Sub dg1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dg1.CellClick
dg1.Rows(e.RowIndex).Cells(3).Value = New Bitmap(app1.My.Resources.stop)
End Sub
But i need get user what image click (Play or Stop)
How to get datagridview image name for Cellclick event?
I tried
dg1.Rows(e.RowIndex).Cells(3).Value.ToString()
But returned "System.Drawing.Image" value i need image value.
Sorry for my bad english.
Thanks for interest

This is how I would get the image. First check if the cell you click is of type DataGridViewImageCell. If it is, try casting the Value property as whatever image format you are expecting.
{
dataGridView1.Columns.Add(new DataGridViewImageColumn());
BitMap bitMap = new BitMap(5,5); // or however you get it from resources
bitMap.Tag = "Play"; // Put the name of the image here
dataGridView1.Rows.Add(bitMap);
}
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var dgv = sender as DataGridView;
if (dgv == null)
return;
var imageCell = dgv[e.ColumnIndex, e.RowIndex] as DataGridViewImageCell;
if (imageCell == null)
return;
var image = imageCell.Value as Bitmap;
if (image == null)
return;
string name = image.Tag as String;
}
Alternatively, you could save the bitmap as a class level variable:
Bitmap playBitmap = New Bitmap(app1.My.Resources.play);
Bitmap stopBitmap = New Bitmap(app1.My.Resources.stop);
then in the CellClick method:
void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
var dgv = sender as DataGridView;
if (dgv == null)
return;
var imageCell = dgv[e.ColumnIndex, e.RowIndex] as DataGridViewImageCell;
if (imageCell == null)
return;
if(imageCell.Value == playBitmap)
{
}
else if (imageCell.Value == stopBitmap)
{
}
}

Related

Trying to stop SpeechSynthesizer in uwp on click of a button

I'm trying to stop SpeechSynthesizer in uwp on click of a button and also trying to start SpeechSynthesizer on clicking same icon again.Any Help would be appreciated for resolution of this issue.
XAML
<Image x:Name="Sound" Source="ABCD/sound_active.png"
RelativePanel.AlignBottomWithPanel="True"
RelativePanel.RightOf="Pause" Tapped="SoundTap"
Margin="17,0,0,0"
Width="40" Height="40"/>
C# code
private void SoundTap(object sender, TappedRoutedEventArgs e)
{
if ((Sound.Source as BitmapImage).UriSource == new Uri("ms-appx:///ABCD/Sound_active.png", UriKind.Absolute))
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));
textToSpeech.Stop();
}
else
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
textToSpeech.Play();
}
}
public async void Prevevent(object sender, TappedRoutedEventArgs e)
{
currentIndex--;
if (currentIndex < 0)
{
currentIndex = 0;
return;
}
Alph_cap.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Cap_" + currentIndex + ".png"));
Alph_small.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Cap_alpha/Sml_" + currentIndex + ".png"));
CapAlphaName.Text = CapsAlpha[currentIndex];
SmallAlphaName.Text = SmallAlpha[currentIndex];
var speechText = this.CapAlphaName.Text;
if (speechText != "")
{
var synth = new SpeechSynthesizer();
var speechStream =await synth.SynthesizeTextToStreamAsync(speechText);
this.textToSpeech.AutoPlay = true;
this.textToSpeech.SetSource(speechStream, speechStream.ContentType);
this.textToSpeech.Play();
}
}
Understanding the question:
Basically you're looking for a toggle switch to turn on and turn off the speech synthesis tts(Text to Speech) in simpler terms.
The Solution:
This couldn't have been simpler enough, never the less, this is how you do it.
Create a Bool property, eg: private IsTTSEnabled = false we'll use this as a flag.
On your Image tap or click, check the current value of IsTTSEnabled and flip it (false if true or true if false) eg: IsTTSEnable = !IsTTSEnable;
Now put a if loop for handling if the TTS is turned on or if it's turned off. Also, since TTS is done using a media element, you don't need to reInitialize your TTS, simple pause and play your media element or start and Stop it as per needs.
So your c# code becomes:
private bool IsTTSEnabled = false;
private void SoundTap(object sender, TappedRoutedEventArgs e)
{
IsTTSEnabled = !IsTTSEnabled;
if(IsTTSEnabled)
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_mute.png"));
textToSpeech.Stop();
}
else
{
Sound.Source = new BitmapImage(new Uri("ms-appx:///ABCD/Sound_active.png"));
textToSpeech.Play();
}
}
Note: This functionality can be easily implemented using Data Binding to provide scalability and ease of management but then the simpler way to do so is like the one I've illustrated

GridView: Get Index on Drop Event

How do I get the index or position where a GridViewItem is being dropped inside the OnDrop event of the GridView? As I have read around that it is possible with GridView.ItemContainerGenerator.ContainerFromItem(item) but for me ItemContainerGenerator is null.
This is my current code:
void gridMain_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
var item = e.Items.First();
var source = sender;
e.Data.Properties.Add("item", item);
e.Data.Properties.Add("source", sender);
}
void gridMain_Drop(object sender, DragEventArgs e)
{
var item = e.Data.Properties.Where(p => p.Key == "item").Single();
object source;
e.Data.Properties.TryGetValue("source", out source);
var s = ((GridView)source).ItemContainerGenerator.ContainerFromItem(item);
}
Any hint or suggestion will be really helpful.
Use GetPosition method of DragEventArgs to find the position where item was dropped and then calculate the actual index, see code snippet below for the handler. Similar question was asked here using this MSDN example as an answer (Scenario 3).
private void GridView_Drop(object sender, DragEventArgs e)
{
GridView view = sender as GridView;
// Get your data
var item = e.Data.Properties.Where(p => p.Key == "item").Single();
//Find the position where item will be dropped in the gridview
Point pos = e.GetPosition(view.ItemsPanelRoot);
//Get the size of one of the list items
GridViewItem gvi = (GridViewItem)view.ContainerFromIndex(0);
double itemHeight = gvi.ActualHeight + gvi.Margin.Top + gvi.Margin.Bottom;
//Determine the index of the item from the item position (assumed all items are the same size)
int index = Math.Min(view.Items.Count - 1, (int)(pos.Y / itemHeight));
// Call your viewmodel with the index and your data.
}
EDIT: Please, consider this as just a prototype. I tried it and it has worked properly, but you may revise it according to your scenario (tweak delay timeout, differentiate more TaskCompletionSource at once, etc.).
The idea is to start a task after Remove action to check whether the item was only removed, or reordered.
private async void observableCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
object removedItem = e.OldItems[0];
var reorderTask = NoticeReorderAsync(removedItem);
try
{
var task = await Task.WhenAny(reorderTask, Task.Delay(100));
if (reorderTask == task)
{
// removedItem was in fact reordered
Debug.WriteLine("reordered");
}
else
{
TryCancelReorder();
// removedItem was really removed
Debug.WriteLine("removedItem");
}
}
catch (TaskCanceledException ex)
{
Debug.WriteLine("removedItem (from exception)");
}
finally
{
tcs = null;
}
}
else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
object addedItem = e.NewItems[0];
bool added = NoticeAdd(addedItem);
if (added)
{
// addedItem was just added, not reordered
Debug.WriteLine("added");
}
}
}
TaskCompletionSource<object> tcs;
private void TryCancelReorder()
{
if (tcs != null)
{
tcs.TrySetCanceled();
tcs = null;
}
}
private Task NoticeReorderAsync(object removed)
{
TryCancelReorder();
tcs = new TaskCompletionSource<object>(removed);
return tcs.Task;
}
private bool NoticeAdd(object added)
{
if (tcs != null)
{
try
{
if (object.Equals(tcs.Task.AsyncState, added))
{
tcs.TrySetResult(added);
return false;
}
else
{
tcs.TrySetCanceled();
return true;
}
}
finally
{
tcs = null;
}
}
return true;
}

DataBinding Snapped Mode Windows 8

Using a GridView, I bind to several items in an observable collection. When I enter snapped mode, my GridView fails to load any data and none of the items are clickable. See attached screenshot. My app is on the left and it says featured and favorites. Here is my code:
public sealed partial class RestaurantHomePage : MenuFinderWin8.Common.LayoutAwarePage
{
MenuFinderAppServiceClient serviceClient;
RestaurantRepository repository;
Geolocator _geolocator = null;
ObservableCollection<RestaurantLocation> items;
public RestaurantHomePage()
{
this.InitializeComponent();
if (!Network.IsNetwork())
{
return;
}
repository = new RestaurantRepository();
serviceClient = new MenuFinderAppServiceClient();
_geolocator = new Geolocator();
items = new ObservableCollection<RestaurantLocation>();
//BindData();
}
void btnAbout_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
SupportUserControl userControl = new SupportUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 200;
f.Height = 200;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnSearch_Click(object sender, RoutedEventArgs e)
{
Flyout f = new Flyout();
LayoutRoot.Children.Add(f.HostPopup); // add this to some existing control in your view like the root visual
// remove the parenting during the Closed event on the Flyout
f.Closed += (s, a) =>
{
LayoutRoot.Children.Remove(f.HostPopup);
};
// Flyout is a ContentControl so set your content within it.
RestaurantSearchUserControl userControl = new RestaurantSearchUserControl();
userControl.UserControlFrame = this.Frame;
f.Content = userControl;
f.BorderBrush = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 223, 58, 51));
f.Width = 600;
f.Height = 400;
f.Placement = PlacementMode.Top;
f.PlacementTarget = sender as Button; // this is an UI element (usually the sender)
f.IsOpen = true;
}
void btnViewFavorites_Click(object sender, RoutedEventArgs e)
{
App.DataMode = Mode.SavedRestaurant;
if (repository.GetGroupedRestaurantsFromDatabase().Count() == 0)
{
MessageDialog messageDialog = new MessageDialog("You have no saved restaurants.", "No Restaurants");
messageDialog.ShowAsync();
}
else
{
this.Frame.Navigate(typeof(RestaurantSearchDetails));
}
}
private async void BindData()
{
try
{
items = await serviceClient.GetSpecialRestaurantsAsync();
List<RestaurantLocation> myFavs = repository.GetRestaurantLocations();
foreach (var a in myFavs)
{
items.Add(a);
}
this.DefaultViewModel["Items"] = items;
}
catch (Exception)
{
MessageDialog messsageDialog = new MessageDialog("The MenuFinder service is unavailable at this time or you have lost your internet connection. If your internet is OK, please check back later.", "Unavailable");
messsageDialog.ShowAsync();
btnAbout.IsEnabled = false;
btnSearch.IsEnabled = false;
btnViewFavorites.IsEnabled = false;
}
myBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
BindData();
// TODO: Assign a bindable collection of items to this.DefaultViewModel["Items"]
}
private void itemGridView_ItemClick_1(object sender, ItemClickEventArgs e)
{
App.CurrentRestaurantLocation = e.ClickedItem as RestaurantLocation;
if (App.CurrentRestaurantLocation != null)
{
Order order = repository.AddOrder(DateTime.Now, string.Empty, App.CurrentRestaurantLocation.ID);
App.CurrentOrder = order;
App.DataMode = Mode.Menu;
this.Frame.Navigate(typeof(RootViewPage));
}
}
}
When you switch to snapped view, your gridView hides, and a ListView shows up. You can see this by checking the Visual State Manager that handles going from one to another in your XAML.
So, Solution is: adapting the ItemTemplate from your ListView as you did with your GridView by Binding to the proper attributes; you may also want to change the Foreground color of your Font. Also, you want to include the IsItemClickEnabled and ItemClick (or SelectionMode and SelectionChanged) on your ListView.

Detect which child control received a Pointer* event

I have a container control that is handling PointerPressed and PointerMoved events.
The container contains a set of buttons.
At the point of handling the event, how can I determine which button actually received it?
mainPage.AddHandler(PointerPressedEvent, new PointerEventHandler(pointerPressedHandler), true);
private void pointerPressedHandler(object sender, PointerRoutedEventArgs e)
{
var p = e.GetCurrentPoint(null); // maybe can be done using position info?
var s = e.OriginalSource as Border; // OriginalSource is a Border, not the Button, and I don't seem to be able to get to the Button from the Border
// todo - determine which button was clicked
}
This works:
private void pointerPressedHandler(object sender, PointerRoutedEventArgs e)
{
var p = e.GetCurrentPoint(null);
var elements = VisualTreeHelper.FindElementsInHostCoordinates(p.Position, mainPage, false);
Button foundButton;
foreach (var item in elements)
{
foundButton = item as Button;
if (foundButton != null)
{
System.Diagnostics.Debug.WriteLine("found button: " + foundButton.Name);
}
}
}

How to Assign Image to object for Saving in Database

I want to Save image to Database.The image is selected by Browsing and is loaded to Imagebox in silverlight application in C#.Net.
I want to assign this loaded image to Object that is used to Saving the data.
Below is my Code.
private void btnBrowse_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog objFileDialog = new OpenFileDialog();
bool? IsSelected = objFileDialog.ShowDialog();
objFileDialog.Filter = "Pictures (*.jpg)|*.jpg";
objFileDialog.FilterIndex = 1;
if (IsSelected == true)
{
BitmapImage bitImage = new BitmapImage();
bitImage.SetSource(objFileDialog.File.OpenRead());
image1.Source = bitImage;
//Image1 is object of Image
}
}
Code of Object that is carrying Data to Save Method in Service File.
private void btnSave_Click(object sender, RoutedEventArgs e)
{
var objData = new ServiceReference1.Data_Registration();
objData .AY_ID = newAcadYearId;
objData .CellNo = txtCellNo.Text;
objData .ImageId = ;
services.DataRegAsync(objAlumni);
}
Please Suggest how can i assign Selected Image to my Object objdata.