I would to put a svg embedded image as ImageSource for a Button in Xamarin.Forms, something like this
<Button Text="Button" ImageSource="resource://fullname.svg">
</Button>
possibly applying a Transformation to svg (from FFImageLoading.Transformations), but this is a plus.
I've tried this syntax
<Button Text="Button"
ImageSource="{ext:ImageResourceExtension fullname.svg}" />
c#
public class ImageResourceExtension : IMarkupExtension
{
private static Assembly Assembly = typeof(ImageResourceExtension).GetTypeInfo().Assembly;
public string Source { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Source == null) return null;
return SvgImageSource.FromResource(Source, Assembly, 32, 32);
}
}
But it's not working.
Moreover I can't make working this syntax
Source="{resource://fullname.svg, Converter={StaticResource SvgImageSourceConverter}}"
Any help?
Thanks
As Jason said, FFImageLoading support SVG files. Follow the steps below.
Create a Resource folder in your Xamarin.Forms instead of Android part. And then add the SVG file as Embedded resource.
Usage: Use SvgCachedImage to show the embedded svg image and use TapGestureRecognizer to simulate the button click event.
<ffimageloadingsvg:SvgCachedImage
HeightRequest="50"
Source="resource://XamarinDemo.Resources.brightness2.svg"
WidthRequest="50">
<ffimageloadingsvg:SvgCachedImage.GestureRecognizers>
<TapGestureRecognizer Tapped="TapGestureRecognizer_Tapped"></TapGestureRecognizer>
</ffimageloadingsvg:SvgCachedImage.GestureRecognizers>
</ffimageloadingsvg:SvgCachedImage>
Do not forget to add namespace.
xmlns:ffimageloadingsvg="clr-namespace:FFImageLoading.Svg.Forms;assembly=FFImageLoading.Svg.Forms"
Updated: We could use SkiaSharp to draw a image with svg file.
MyControl.cs
public class MyControl : Frame
{
private readonly SKCanvasView _canvasView = new SKCanvasView();
public MyControl()
{
Padding = new Thickness(0);
BackgroundColor = Color.Transparent;
Content = _canvasView;
_canvasView.PaintSurface += CanvasViewOnPaintSurface;
}
public static readonly BindableProperty ImageProperty = BindableProperty.Create(
nameof(Image), typeof(string), typeof(MyControl), default(string), propertyChanged: RedrawCanvas);
public string Image
{
get => (string)GetValue(ImageProperty);
set => SetValue(ImageProperty, value);
}
private static void RedrawCanvas(BindableObject bindable, object oldvalue, object newvalue)
{
MyControl svgIcon = bindable as MyControl;
svgIcon?._canvasView.InvalidateSurface();
}
private void CanvasViewOnPaintSurface(object sender, SKPaintSurfaceEventArgs e)
{
SKCanvas canvas = e.Surface.Canvas;
canvas.Clear();
using (Stream stream = GetType().Assembly.GetManifestResourceStream(Image))
{
SkiaSharp.Extended.Svg.SKSvg svg = new SkiaSharp.Extended.Svg.SKSvg();
svg.Load(stream);
SKImageInfo info = e.Info;
canvas.Translate(info.Width / 2f, info.Height / 2f);
SKRect bounds = svg.ViewBox;
float xRatio = info.Width / bounds.Width;
float yRatio = info.Height / bounds.Height;
float ratio = Math.Min(xRatio, yRatio);
canvas.Scale(ratio);
canvas.Translate(-bounds.MidX, -bounds.MidY);
canvas.DrawPicture(svg.Picture);
}
}
}
Usage:
<local:MyControl
HeightRequest="50"
Image="XamarinDemo.Resources.brightness2.svg"
WidthRequest="50" />
And you could use TapGestureRecognizer to simulate the button click event.
Updated original image resource extension class for Xamarin. OP's class had two issues:
Missing ContentProperty attribute which allows to skip "Source" property name.
Part where partial resource name is converted to a full resource name.
Added optional "Assembly" property, which allows to specify different assembly. In the code, you can also get the full name, resource path, and ImageSource object with the optional replace string map applied, which allows to modify the original SVG content on the fly, e.g. colors).
Usage:
<ff:SvgCachedImage Source="{ImageFromResource file_name.svg}" />
<ff:SvgCachedImage Source="{ImageFromResource Icons/file_name.svg}" />
<Image Source="{ImageFromResource file_name.png}" />
<Image Source="{ImageFromResource file_name.png, Assembly=MyAssembly}" />
ImageFromResourceExtension class:
using FFImageLoading.Svg.Forms;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
/// <summary>
/// Get image source from assembly resource by using partial name.
/// </summary>
/// <example>
/// <ff:SvgCachedImage Source="{ImageFromResource file_name.svg}" />
/// <ff:SvgCachedImage Source="{ImageFromResource Icons/file_name.svg}" />
/// <ff:Image Source="{ImageFromResource file_name.png}" />
/// <ff:Image Source="{ImageFromResource file_name.png, Assembly=MyAssembly}" />
/// </example>
/// <remarks>
/// Parameter format without extension:
/// Source="resource://{AssemblyName}.{PathName}.{FileName}"
/// </remarks>
[ContentProperty(nameof(Source))]
public class ImageFromResourceExtension : IMarkupExtension
{
public static Assembly DefaultAssembly = typeof(ImageResourceExtension).GetTypeInfo().Assembly;
public string Source { get; set; }
public string Assembly { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
=> GetResourcePath(Source, Assembly);
public static string GetResourcePath(string name, string assembly = null)
=> "resource://" + GetFullName(name, assembly);
public static string GetFullName(string name, string assembly = null)
{
if (string.IsNullOrEmpty(name))
return null;
// Replace folder separators with dots.
name = name.Replace('/', '.');
// Use different assembly if specified.
var asm = string.IsNullOrEmpty(assembly)
? DefaultAssembly
: System.Reflection.Assembly.Load(assembly);
// Find full name of the resource by partial name.
var fullName = asm.GetManifestResourceNames()
.FirstOrDefault(x => x.EndsWith("." + name));
return fullName;
}
public static ImageSource GetImage(string name, string assembly = null, StringDictionaryCollection map = null)
{
var fullName = GetFullName(name);
if (fullName == null)
return null;
// Use different assembly if specified.
var asm = string.IsNullOrEmpty(assembly)
? DefaultAssembly
: System.Reflection.Assembly.Load(assembly);
// Return image source.
return fullName.EndsWith(".svg", StringComparison.OrdinalIgnoreCase)
? SvgImageSource.FromResource(fullName, asm, replaceStringMap: map)
: ImageSource.FromResource(fullName, asm);
}
}
Related
I am having some issues with bindings using xamarin forms IOS.
I have bindings That display a loading label in the center of the screen when the first page appears.
After The listview loads the data the Loading label is hidden through bindings and the list view is displayed.
In the android project I have in this repo Xamarin forms IOS Android Test
It works fine. In the ios in the repro project the loading label is hidden when the application first loads and will display if you tap on the screen.
If you continue the loading label disappears and you see a blank screen but if you tap on the screen again the list data view appears.
I am thinking this is a bug with xamarin but I am hoping that my bindings are just incorrect. I work around for this issue would be appreciated.
I also two other problems. When you click on a list view item and the navigate back the data is not refreshed because onappearing is not triggered.
In android it is triggered without an issue. Sometimes onappearing does trigger after you tap on the screen like the steps mentioned above.
The last issue is that when switching between tabs IOS does not trigger on appearing. With android it does.
Any help on this issue would be greatly appreciated. I have done extensive searching on solutions for these problems and have yet to find and answer.
Thanks!
Here is some code snippets to help. This code is also in the GitHub repo if you want to test it out.
In XAML
<Label x:Name="xEmptyListView"
FontSize="16"
HorizontalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
VerticalOptions="CenterAndExpand"
Text="{Binding ListViewVisibleText, Mode=TwoWay}"
IsVisible="{Binding IsListViewLabelEmptyVisible, Mode=TwoWay }"/>
<ListView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="true"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected"
IsVisible="{Binding IsListViewVisible, Mode=TwoWay}"
IsEnabled="{Binding IsActivityRunning, Mode=TwoWay, Converter={StaticResource InverseBooleanConverter}}">
ViewModel
private bool activityRunning { get; set; }
public bool IsActivityRunning
{
get { return activityRunning; }
set
{
if (activityRunning == value)
return;
activityRunning = value;
OnPropertyChanged("IsActivityRunning");
}
}
private string listViewVisibleText { get; set; }
public string ListViewVisibleText
{
get { return listViewVisibleText; }
set
{
if (listViewVisibleText == value)
return;
listViewVisibleText = value;
OnPropertyChanged("ListViewVisibleText");
}
}
private bool listViewLabelEmptyVisible { get; set; }
public bool IsListViewLabelEmptyVisible
{
get
{
if (Items == null || Items.Count == 0)
{
if (IsBusy)
{
ListViewVisibleText = "Loading...";
}
else
{
ListViewVisibleText = "No Items found";
}
listViewLabelEmptyVisible = true;
}
else
{
ListViewVisibleText = string.Empty;
listViewLabelEmptyVisible = false;
}
OnPropertyChanged("IsListViewLabelEmptyVisible");
return listViewLabelEmptyVisible;
}
}
private bool listViewVisible { get; set; }
public bool IsListViewVisible
{
get
{
if (Items == null || Items.Count == 0)
{
listViewVisible = false;
}
else
{
listViewVisible = true;
}
OnPropertyChanged("IsListViewVisible");
return listViewVisible;
}
}
XAML.cs
protected override void OnAppearing()
{
base.OnAppearing();
viewModel.LoadItemsCommand.Execute(null);
}
I am using notify property changed. It is standard code
This is what my view model inherits for the notifyproperty changed
public class ItemsViewModel : BaseViewModel
which base viewmodel inherits from the observable object
public class BaseViewModel : ObservableObject
When you create a test xamarin project this is the way it looks.
public class ObservableObject : INotifyPropertyChanged
{
/// <summary>
/// Sets the property.
/// </summary>
/// <returns><c>true</c>, if property was set, <c>false</c> otherwise.</returns>
/// <param name="backingStore">Backing store.</param>
/// <param name="value">Value.</param>
/// <param name="propertyName">Property name.</param>
/// <param name="onChanged">On changed.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
protected bool SetProperty<T>(
ref T backingStore, T value,
[CallerMemberName]string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
/// <summary>
/// Occurs when property changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises the property changed event.
/// </summary>
/// <param name="propertyName">Property name.</param>
protected void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Activity running gets set when items are loading etc.
This all works on android. IOS it doesn't.
Sometimes the navigation behaviours are different from iOS and Android. If OnAppearing is not working, you can try to use MessageCenter https://developer.xamarin.com/guides/xamarin-forms/application-fundamentals/messaging-center/ to trigger data loading.
I figured this one out. The way I was handling the bindings with showing the label and hiding the list view and vice versa was interfering with the way that IOS handles requests. I removed the bindings and set the controls directly using a property changed handler on the list view. That fixed the on appearing problems for the tabs, the back button etc.
In Orchard CMS I have a service that pulls data from an external data source, and loads the data into an Orchard Content Part. The Part has a migration that welds it with a title part, and I have a route so that my controller is being hit via a URL:
I am using a controller to access the item via a URL, much like the Blog Part controller. However I can't render my part...
The Blog Controller does similar to the following:
var asset = _assetService.Get(1234);
if (asset == null) return HttpNotFound();
var model = _services.ContentManager.BuildDisplay(asset);
return new ShapeResult(this, model);
But if I do this, the 'BuildDisplay' method looks for asset.ContentItem but this is null, despite deriving my part from 'ContentPart'.
What do I need to do to get my data to display?
If I understand correctly, you are trying to display only one part, and not a whole content item.
To display a single shape, you can do the following:
private readonly IAssetService _assetService;
public MyController(IShapeFactory shapeFactory, IAssetService assetService) {
_assetService = assetService;
Shape = shapeFactory;
}
public dynamic Shape { get; set; }
public ActionResult MyAction(int assetId) {
var asset = _assetService.Get(1234);
if (asset == null) return HttpNotFound();
// the shape factory can call any shape (.cshtml) that is defined
// this method assumes you have a view called SomeShapeName.cshtml
var model = Shape.SomeShapeName(asset);
return new ShapeResult(this, model);
}
!!Note:
This does not kick of the (display)driver of the part, it only returns the .cshtml with the given model
By having my part deriving from ContentPart, I can use the following Controller method:
private readonly IAssetService _assetService;
private readonly IOrchardServices _services;
public MyController(IShapeFactory shapeFactory, IAssetService assetService, IOrchardServices services) {
_assetService = assetService;
_services = services;
Shape = shapeFactory;
}
public dynamic Shape { get; set; }
public ActionResult MyAction(int assetId) {
var asset = _assetService.Get(1234);
if (asset == null) return HttpNotFound();
// this method assumes you have a view called Parts.Asset.cshtml (see the AssetPartDriver)
var model = _services.ContentManager.New("Asset");
var item = contentItem.As<AssetPart>();
item.Populate(asset) // Method that just populates the service loaded object into the ContentPart
return new ShapeResult(this, _services.ContentManager.BuildDisplay(item));
}
This will use the 'AssetPartDriver':
public class AssetPartDriver : ContentPartDriver<AssetPart>
{
protected override DriverResult Display(AssetPart part, string displayType, dynamic shapeHelper)
{
return ContentShape("Parts_Asset", () => shapeHelper.Parts_Asset()); // Uses Parts.Asset.cshtml
}
}
And in conjunction with the 'Placement.info' file renders on the screen:
<Placement>
<Match ContentType="Asset">
<Match DisplayType="Detail">
<Place Parts_Asset="Content"/>
</Match>
</Match>
</Placement>
The migration file combines my web service part with other Orchard parts:
public class Migrations : DataMigrationImpl
{
public int Create()
{
ContentDefinitionManager.AlterTypeDefinition("Asset", cfg => cfg
.WithPart("AssetPart")
.WithPart("AutoroutePart", builder => builder
.WithSetting("AutorouteSettings.AllowCustomPattern", "True"))
.Listable()
.Securable()
.Creatable(false));
ContentDefinitionManager.AlterPartDefinition("AssetPart", part => part
.WithDescription("A part that contains details of an individual Web Service loaded asset."));
return 1;
}
}
These additional parts are not yet used, but can be populated during creation and displayed individually using the placement file.
This is the first step of what I was trying to achieve!!
I am trying to configure mail target by params from app.config using custom renderer. My NLog Mail Target:
<target name="AlertMail" xsi:type="Mail"
to="${mailTo}"
from="${mailFrom}"
html="true"
encoding="${enc}"
subject="[APPNAME][${mailEnv}][${instanceName}][${logger:uppercase=true}]"
smtpServer="${smtpHost}"
smtpAuthentication="${smtpAuth}"
smtpUserName="${smtpUserName}"
smtpPassword="${smtpPassword}"
header="${mailHtmlHeader}${mailBodyHeader}"
layout="${mailMessage}"
footer="${mailBodyFooter}${mailHtmlFooter}"/>
NLog Variables:
<variable name="${enc}" value="${app-settings:default.encoding}" />
<variable name="${smtpAuth}" value="${app-settings:alerting.smtp.authentication}" />
NLog Layout Renderer:
[LayoutRenderer("app-settings")]
public class AppSettingsRenderer : LayoutRenderer
{
[RequiredParameter]
[DefaultParameter]
public string Key { get; set; }
protected override void Append(StringBuilder builder, NLog.LogEventInfo logEvent)
{
var param = ConfigurationManager.AppSettings[this.Key];
builder.Append(param);
}
}
I'm getting error
Error when setting property 'Encoding' on Mail Target[AlertMail]
at NLog.Internal.PropertyHelper.SetPropertyFromString(Object o, String name, String value, ConfigurationItemFactory configurationItemFactory)
at NLog.Config.XmlLoggingConfiguration.ConfigureObjectFromAttributes(Object targetObject, NLogXmlElement element, Boolean ignoreType)
at NLog.Config.XmlLoggingConfiguration.ParseTargetElement(Target target, NLogXmlElement targetElement)
at NLog.Config.XmlLoggingConfiguration.ParseTargetsElement(NLogXmlElement targetsElement)
at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(NLogXmlElement nlogElement, String baseDirectory)
at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String baseDirectory)
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
at NLog.Config.XmlLoggingConfiguration..ctor(String fileName)
at Common.Logging.NLog.NLogLoggerFactoryAdapter..ctor(NameValueCollection properties) in D:\Project\GSJSJZB\GSJ_SJZB\Common.Logging.NLog\Logging\NLog\NLogLoggerFactoryAdapter.cs:line 109
and it's obviously because LayoutRenderer handling properties only type of Layout. The property smtpAuthentication has the same issue. How to workaround this limitation to use params from appconfig for types other than Layout?
I resolve this issue using custom Target derived from MailTarget:
[Target("MyMail")]
class MyMailTarget : MailTarget
{
/// <summary>
/// Wrapper for enum to use placeholders
/// </summary>
[DefaultValue("None")]
public Layout SmtpAuth { get; set; }
protected override void Write(NLog.Common.AsyncLogEventInfo logEvent)
{
Write(new[] {logEvent});
}
protected override void Write(NLog.Common.AsyncLogEventInfo[] logEvents)
{
var renderedAuthType = SmtpAuth.Render(logEvents.Last().LogEvent);
SmtpAuthenticationMode mode;
if (Enum.TryParse(renderedAuthType, true, out mode))
SmtpAuthentication = mode;
else
{
InternalLogger.Warn("Could not convert '{0}' to SmtpAuthenticationMode, valid values are None, Basic and Ntlm.");
throw new NLogRuntimeException(String.Format("Cannot render SmtpAuthentication. SmtpAuth = {0}", renderedAuthType));
}
base.Write(logEvents);
}
}
Using:
<extensions>
<add assembly="AssemplyNameWithMyMailTarget" />
</extensions>
<variable name="smtpAuth" value="${app-settings:alerting.SMTP.Authentication}"/>
<!-- smtpAuth - my custom attribute -->
<target name="AlertMail" xsi:type="MyMail"
to="${mailTo}"
from="${mailFrom}"
subject="[APPNAME][ALERT][${mailEnv}][${instanceName}]"
smtpServer="${smtpHost}"
smtpAuth="${smtpAuth}"
smtpUserName="${smtpUserName}"
smtpPassword="${smtpPassword}"
layout="${longdate}${newline}${message}${newline}"
/>
I've 3 of .NET Projects.
One of these project is an ASP.Net Web Form Application named Index. And the other projects are listed below
Index.Database Project is Database Layer
Index.Platform Project is Bussiness layer.
In bussiness layer im loading UserControls. There is information bout these UserControls in db. (Path, ascx file, name, Title, Content, Positions etc )
In bussiness layer i created a class drived from UserControl named ModuleControl.
Index.Platform referenced by System.Web.dll also uses Using System.Web.UI.WebControls.
I'm planning to use this ModuleControl fields in my loaded UserControls. There is another class named IndexSite instanced on Default.aspx's Load_Page event.
namespace Index.Platform.Modules
{
public class ModuleControl : System.Web.UI.UserControl
{
public string Title { get; set; }
public bool ShowTitle { get; set; }
public string Content { get; set; }
public ModuleControl()
{
}
}
}
//Index.Platform.IndexSite
private void InitializeModules(System.Web.UI.Page page)
{
string mPath = null;
try
{
ModuleDictionaryList = DBFactory.LoadModules();
PositionList = DBFactory.PositionList;
ModuleList = DBFactory.ModuleList;
foreach (KeyValuePair<string, List<module>> pair in ModuleDictionaryList)
{
foreach (var item in pair.Value)
{
mPath = "/Modules/" + item.Name + "/" + item.Name + ".ascx";
iControl = (ModuleControl)page.LoadControl(mPath);
ShowTitle = Convert.ToBoolean(item.ShowTitle);
iControl.ShowTitle = ShowTitle;
iControl.Title = item.Title;
iControl.Content = item.Content;
panel = (PlaceHolder)page.Master.FindControl(item.Position);
panel.Controls.Add(iControl);
//HttpContext.Current.Response.Write(item.Position + "<br>");
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
this class takes an argument from Default.aspx. Page sends its self.
protected void Page_Load(object sender, EventArgs e)
{
IndexSite site = IndexSite.Instance.Create(this);
}
Yes, In Bussines layer I use LoadControl method to load USerControl also im adding these controls to a panel control which is in MasterPage (PlaceHolder).
My problem is in this line: iControl = (ModuleControl)page.LoadControl(mPath);
I cant cast UserControl to ModuleControl. Remember this ModuleControl drived from UserControl and all of my ascx file drived from ModuleControl class.
Throws this error: "Unable to cast object of type 'ASP.modules_mod_login_mod_login_ascx' to type 'Index.Platform.Modules.ModuleControl'."
If i do these proccess in Main application there is no error for casting ModuleControl.
When id seperate my application to 3. I stuck here.
There is a program that I am working on and Im absolutly lost even at how to begin this. I am using Visual Studio C# Windows App Form.
What I need to do is allow the user to enter any path location they want and the program will return the Name of the file/folder; Path; date and size, and this will also be done for sub directories.
I found some code in the MSDN site and I am trying to use it and modify it for the first part of this project, but keep receiving error messages. Some of the messages indicate that there is more than one entry ie (static void Main() and using namespace Detailed).
This is what I have so far, a form with rich text box and the FolderBrowserDialog and it seems as I can't get beyond this point without so many errors.
This is under Form1.Designer.cs:
<i>namespace Detailed
{
partial class Form1
{
///
/// Required designer variable.
///
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
this.richTextBox1 = new System.Windows.Forms.RichTextBox();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.SuspendLayout();
//
// folderBrowserDialog1
//
this.folderBrowserDialog1.HelpRequest += new System.EventHandler(this.folderBrowserDialog1_HelpRequest);
//
// richTextBox1
//
this.richTextBox1.Location = new System.Drawing.Point(12, 32);
this.richTextBox1.Name = "richTextBox1";
this.richTextBox1.Size = new System.Drawing.Size(167, 23);
this.richTextBox1.TabIndex = 0;
this.richTextBox1.Text = "";
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.richTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.Load += new System.EventHandler(this.Form1_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FolderBrowserDialog folderBrowserDialog1;
private System.Windows.Forms.RichTextBox richTextBox1;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
}
}
For the For1.cs this is what I have so far:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
public class FolderBrowserDialogExampleForm : System.Windows.Forms.Form
{
private FolderBrowserDialog folderBrowserDialog1;
private OpenFileDialog openFileDialog1;
private RichTextBox richTextBox1;
private MainMenu mainMenu1;
private MenuItem fileMenuItem, openMenuItem;
private MenuItem folderMenuItem, closeMenuItem;
private string openFileName, folderName;
private bool fileOpened = false;
public partial class Form1 : Form
{
public Form1()
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
}
private void InitializeComponent()
{
this.SuspendLayout();
//
// FolderBrowserDialogExampleForm
//
this.ClientSize = new System.Drawing.Size(284, 262);
this.Name = "FolderBrowserDialogExampleForm";
this.ResumeLayout(false);
}
}
I'm still new to programing and hope I can get this figured out asap as I was requested to have this no later than Thursday morning est. I had the Rich TextBox in the Form, but removed it because of too many errors.
This is the code I found. I know this is just part of what I need to do, but when reading through the code I noticed that maybe I can apply what is needed to the form and then break up the code and put the pieces of code where I need them. This is the code I am following
Here is an error message I am receiving with Form1.Designer.cs - there are 14 of these same errors:
‘Detailed.form1’ does not contain a definition for ‘Form1_Load’ and no extension method ‘Form1_Load’ accepting a first argument of type ‘Detailed.Form1’ could be found (are you missing a using directive or an assembly reference?)
The first thing you want is a dialog prompting the user for a directory.
So get rid of all that code, start a new project win form and place a textbox in your form and a button in your form.
Simple enough one text box and one button. Now in the click event of your button "Browse", have you, you write code to open an instance of the FolderBrowserDialog class and you .ShowDialog().
To get this path:
Here is a sample screen output:
The code is fairly straightforward, look at my picture and how much code i have to do this.