Drag and Drop Storagefile from one listview to another - c#

I have 2 list views and I'm trying to drag an item from one to the other.
The typeof item is a storagefile.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items;
files.Add(file);
e.Data.SetStorageItems(files);
}
private void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
//if (e.DataView.Contains(StandardDataFormats.StorageItems))
//{
// var items = await e.DataView.GetStorageItemsAsync();
// if (items.Count > 0)
// {
// var storageFile = items[0] as StorageFile;
// ListC.Items.Add(storageFile);
// }
// }
}
I've tried everything I can think of to drop the storage file into the other listview and show the display name... All I've been able to display are types and stuff.
Can anyone help me?

I've solved it after hours or trying.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
//f.MessageBox(e.Items.First().GetType().ToString());
try
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items.First() as StorageFile;
files.Add(file);
e.Data.SetStorageItems(files);
//e.Data.SetData(StandardDataFormats.Text, e.Items.);
}catch(Exception ex)
{
f.MessageBox(ex.Message);
}
}
private async void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
//IReadOnlyList<IStorageItem> files = await e.DataView.GetStorageItemsAsync();
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
try
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
var storageFile = items[0] as StorageFile;
ListC.Items.Add(storageFile.Name);
}
}
}catch
{
f.MessageBox("nope");
}

Related

Load an Image to a Canvas Control from a File Picker

What I'm trying to do in a UWP app with Win2D:
User pressed a button to add an image and picks their file.
That file gets loaded as a resource for a Canvas Control.
The image then gets rendered to the current drawing session
When the button is clicked:
private async void btnAddPicture_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
overlayPictureFile = await picker.PickSingleFileAsync();
if (overlayPictureFile == null)
{
txbNotification.Text = "File Picking cancelled";
return;
}
else
{
txbNotification.Text = "Picture Loaded";
}
using (IRandomAccessStream stream = await overlayPictureFile.OpenAsync(FileAccessMode.Read))
{
var device = new CanvasDevice();
createdBitmap = await CanvasBitmap.LoadAsync(device, stream);
}
}
In the drawing function:
void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
if (createdBitmap != null)
{
args.DrawingSession.DrawImage(createdBitmap, Drawing.FindDefaultRect());
}
drawingCanvas.Invalidate();
}
Everything will compile but the moment I press the button to add an image it breaks here.
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
#endif
I'm already loading some image in this, but those are all part of the program and are created before the canvas is created with these. Not sure how to do that with ones the user picks.
private void drawingCanvas_CreateResources(CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
{
args.TrackAsyncAction(CreateResourcesAsync(sender).AsAsyncAction());
}
private async Task CreateResourcesAsync(CanvasControl sender)
{
logo = await CanvasBitmap.LoadAsync(sender, new Uri("ms-appx:///Assets/Pictures/Logo_BlackBorders.png"));
}
Update:
Where I currently am drawing things. This is the canvas I'm trying to add the image to.
void CanvasControl_Draw(CanvasControl sender, CanvasDrawEventArgs args)
{
//Drawing a bunch of stuff
}
private void drawingCanvas_CreateResources(CanvasControl sender, Microsoft.Graphics.Canvas.UI.CanvasCreateResourcesEventArgs args)
{
args.TrackAsyncAction(CreateResourcesAsync(sender).AsAsyncAction());
}
private async Task CreateResourcesAsync(CanvasControl sender)
{
logo = await CanvasBitmap.LoadAsync(sender, new Uri("ms-appx:///Assets/Pictures/Logo.png"));
}
Load an Image to a Canvas Control from a File Picker
For your scenario, you could get CanvasDrawingSession with CreateDrawingSession method. And then use this drawingsession to draw picked image to current CanvasControl.
For example.
private async void btnAddPicture_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.FileTypeFilter.Add(".png");
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
var overlayPictureFile = await picker.PickSingleFileAsync();
if (overlayPictureFile == null)
{
return;
}
else
{
}
using (IRandomAccessStream stream = await overlayPictureFile.OpenAsync(FileAccessMode.Read))
{
//get canvascontrol's Device property.
CanvasDevice device = drawingCanvas.Device;
createdBitmap = await CanvasBitmap.LoadAsync(device, stream);
//use device property to make renderer
var renderer = new CanvasRenderTarget(device,
createdBitmap.SizeInPixels.Width,
createdBitmap.SizeInPixels.Height, createdBitmap.Dpi);
//make ds with above renderer.
using (var ds = renderer.CreateDrawingSession())
{
ds.DrawImage(createdBitmap, 0, 0);
}
}
}

How to Insert bitmap image to sqlite database on Windows phone 8.1 c#

I have managed to pick an image from the phones library and display it. this is the code. Question is how do i Insert this image into my Sqlite database of contacts and retrieve it and display it again after getting the image? Here is my code. A detailed step by step instruction would be appreciated from here.
namespace Mobile_Life.Pages
{
public sealed partial class NextOFKin_Update_Delete : Page
{
int Selected_ContactId = 0;
DatabaseHelperClass Db_Helper = new DatabaseHelperClass();
Contacts currentcontact = new Contacts();
CoreApplicationView view;
public NextOFKin_Update_Delete()
{
this.InitializeComponent();
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
view = CoreApplication.GetCurrentView();
}
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await StatusBar.GetForCurrentView().ShowAsync();
Selected_ContactId = int.Parse(e.Parameter.ToString());
currentcontact = Db_Helper.ReadContact(Selected_ContactId);//Read selected DB contact
namestxt.Text = currentcontact.Name;//get contact Name
relationtxt.Text = currentcontact.Relation;//get contact relation
phonetxt.Text = currentcontact.PhoneNumber;//get contact PhoneNumber
}
private void Update_click(object sender, RoutedEventArgs e)
{
currentcontact.Name = namestxt.Text;
currentcontact.Relation = relationtxt.Text;
currentcontact.PhoneNumber = phonetxt.Text;
Db_Helper.UpdateContact(currentcontact);//Update selected DB contact Id
Frame.Navigate(typeof(NextOfKin));
}
private void Delete_click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteContact(Selected_ContactId);//Delete selected DB contact Id.
Frame.Navigate(typeof(NextOfKin));
}
private void profile_img(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(FileAccessMode.Read);
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
profile.ImageSource = bitmapImage;
}
}
}
The best way would be NOT to store the image in SQLite. Just copy it to your ApplicationData.Current.LocalFolder and save the path.
If you really want to store the BitmapImage in SQLite, just convert it to byte array: Convert a bitmapimage to byte[] array for storage in sqlite database

Drag and Drop only PDF files

I have the following code that list the files that i drag in a listbox.
now i need to filter so it can only list PDF files and discard the rest.
private void Form1_Load(object sender, EventArgs e)
{
listBoxFiles.AllowDrop = true;
listBoxFiles.DragDrop += listBoxFiles_DragDrop;
listBoxFiles.DragEnter += listBoxFiles_DragEnter;
}
private void listBoxFiles_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
listBoxFiles.Items.Add(file);
}
Try this:
private void listBoxFiles_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string file in files)
{
if (Path.GetExtension(file) == "pdf")
{
listBoxFiles.Items.Add(file);
}
}
}
Also, if it works - you can make it in one line with Linq

Directory Getfiles not working as I expected

I am using express VS-2015.I have an folderbrowser control,textbox1 and button control.
I need to retrieve multiple file type and show it on listbox.I am wondering what is wrong in my code.It is not showing any error but not showing any files, despite of file type present in a folder.any suggestion.
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
string[] extensions = { ".xml", ".ddg" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*", SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
listBox1.Items.AddRange(dizin);
}

Add, Edit, Remove items from a List<String>

I have a list of Strings, List<String>.
I want to be able to open a form, showing the contents of this list, and allow the user to add, edit, and remove items from the list during run time.
I've been looking at ListView, but it isn't clicking for me. I'm not sure if that's because it isn't the right solution or that I don't get it.
What is the proper solution for what I want to do?
Chuck
You can use a list view and a context menu for your target:
try this code:
List<string> listofstring = new List<string>() {"A","B","C" };
private void Form1_Load(object sender, EventArgs e)
{
FillLstView();
}
private void Additem_Click(object sender, EventArgs e)
{
listofstring.Add("New Item");
FillLstView();
}
private void RemoveItem_Click(object sender, EventArgs e)
{
listofstring.RemoveAt(lstview.FocusedItem.Index);
EditItem.Enabled = false;
RemoveItem.Enabled = false;
FillLstView();
}
private void lstview_SelectedIndexChanged(object sender, EventArgs e)
{
RemoveItem.Enabled = true;
EditItem.Enabled = true;
}
private void EditItem_Click(object sender, EventArgs e)
{
string input = Microsoft.VisualBasic.Interaction.InputBox("Enter Edit", "Title", "Edited", 0, 0);
if (input != "")
{
listofstring[lstview.FocusedItem.Index] = input;
EditItem.Enabled = false;
RemoveItem.Enabled = false;
FillLstView();
}
}
private void FillLstView()
{
lstview.Clear();
foreach (var item in listofstring)
{
lstview.Items.Add(item);
}
}
Result
Download Project

Categories