Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4230602
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T01:52:58+00:00 2026-05-21T01:52:58+00:00

A good day dear developers. My name is Danny. This is my first post

  • 0

A good day dear developers. My name is Danny.

This is my first post here on Stackoverflow… as much as i am fairly new to the .NET Framework.
I did search quite thoroughly through several forums, but am apparently looking with my nose.

My question is this:
I am writing a piece of script that reads out how many .txt-files there exist within a directory.

Then it creates the amount of GroupBoxes (with each a grid) as there are .txt’s through a ‘foreach’ command.
And within that same foreach-command, i use: Grid.Children.Add(control).
Per foreach-iteration there are 2 controls to be added to the generated grid.

The problem:
It does not do that… well sort of.
It only makes 2 iterations, regardless of how many .txt’s there are.
And within the Output-dialog it says: A first chance exception of type 'System.ArgumentException' occurred in PresentationCore.dll.

In case my explanation is not as clear as i meant to, here follows my script, and thanks for reading:

using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Threading;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Threading;
using System.Windows.Controls.Primitives;

namespace Notes
{
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }


    // Create Objects
    public TextBox tBox = new TextBox();
    public Label fLabel = new Label();
    public GroupBox group = new GroupBox();
    public Grid groupGrid = new Grid();


    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        // Global Variables
        int Increment = 1;
        string Dir = "DIRECTORY_HERE";
        int leftMargin = 10;
        int betweenMargin = 10;

        // GroupBox Initials
        group.Height = this.Height - 125;
        group.Margin = new Thickness(0, 75, 0, 0);
        group.HorizontalAlignment = HorizontalAlignment.Left;
        group.VerticalAlignment = VerticalAlignment.Top;

        // Grid Initials
        groupGrid.Width = leftMargin;
        groupGrid.Height = group.Height;
        groupGrid.Margin = new Thickness(0, 0, 0, 0);
        groupGrid.HorizontalAlignment = HorizontalAlignment.Left;
        groupGrid.VerticalAlignment = VerticalAlignment.Top;

        // Label Initials
        fLabel.Width = 260;
        fLabel.Height = 28;
        fLabel.HorizontalAlignment = HorizontalAlignment.Left;
        fLabel.VerticalAlignment = VerticalAlignment.Top;
        fLabel.Margin = new Thickness(0, 0, 0, 0);

        // TextBox Intitials
        tBox.Width = 100;
        tBox.Height = groupGrid.Height;
        tBox.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
        tBox.HorizontalAlignment = HorizontalAlignment.Left;
        tBox.VerticalAlignment = VerticalAlignment.Top;
        tBox.Foreground = new SolidColorBrush(Colors.DarkCyan);
        tBox.Background = new SolidColorBrush(Colors.Red);
        tBox.TextWrapping = TextWrapping.NoWrap;



        // Get paths of all files within given directory.
        string[] Notes = Directory.GetFiles(Dir, "*.*", SearchOption.TopDirectoryOnly).ToArray();

        foreach (string Note in Notes)
        {
            Console.WriteLine("NOTE: " + Note);

            // Text settings
            FileInfo fi = new FileInfo(Note);
            TextReader tr = new StreamReader(fi.ToString());
            tBox.Name = "tBox" + Increment.ToString();
            tBox.Text = tr.ReadToEnd();
            tBox.Margin = new Thickness(betweenMargin, 0, 0, 0);

            // FileLabel settings
            fLabel.Name = "fLabel" + Increment.ToString();

            // GroupGrid settings
            groupGrid.Name = "groupGrid" + Increment.ToString();
            groupGrid.Children.Add(tBox);               //error
            groupGrid.Children.Add(fLabel);             //error

            // group settings
            group.Width = leftMargin + (tBox.Width * Increment) + (betweenMargin * Increment);
            group.Content = groupGrid;

            // Increment
            Increment++;
        }


        NotesDoc.Children.Add(group);
    }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T01:52:58+00:00Added an answer on May 21, 2026 at 1:52 am

    You are attempting to program a WPF application like you would a Windows Forms app. Believe me, you can accomplish your goal much easier if you actually learn some of the WPF development patterns (such as MVVM).

    For example, this can be easily accomplished using an ObservableCollection holding all (not sure how you are doing this) FileInfo instances (one for each file).

    You then bind a ItemsControl‘s ItemsSource property to this collection. Now, whenever you add a new FileInfo instance to the ObservableCollection the ItemsControl will add a new row and bind that row to the instance.

    Of course, the default template for each row just calls .ToString() on each instance, so you’ll get a bunch of rows that contains “System.IO.FileInfo”. To show information about each FileInfo, you can add a DataTemplate to ItemsSource.ItemTemplate and add controls that bind to the public properties of the FileInfo.

    It is VERY important to understand some of these basic patterns when developing WPF applications. Attempting to interact with the UI from the codebehind in the manner you are attempting is VERY HARD to do. Many of the UI patterns for WPF applications are optimized for use in XAML; attempting to interact with these (such as attached properties) from the codebehind can be extremely confusing and counterintuitive.


    Here’s a simple MVVM sample I updated. To use this, create a new solution (3.5 or greater) called SimpleMVVM. Create a new class in the root of the project called ViewModel and add the following code to the file:

    /// <summary>
    /// A simple ViewModel to demonstrate MVVM
    /// </summary>
    public sealed class ViewModel : DependencyObject, IDataErrorInfo
    {
        #region Properties
        #region DirectoryName
        /// <summary>
        /// The <see cref="DependencyProperty"/> for <see cref="DirectoryName"/>.
        /// </summary>
        public static readonly DependencyProperty DirectoryNameProperty =
            DependencyProperty.Register(
                DirectoryNameName,
                typeof(string),
                typeof(ViewModel),
                new UIPropertyMetadata(null));
    
        /// <summary>
        /// The name of the <see cref="DirectoryName"/> <see cref="DependencyProperty"/>.
        /// </summary>
        public const string DirectoryNameName = "DirectoryName";
    
        /// <summary>
        /// 
        /// </summary>
        public object DirectoryName
        {
            get { return (object)GetValue(DirectoryNameProperty); }
            set { SetValue(DirectoryNameProperty, value); }
        }
        #endregion
    
        #region SelectedFile
        /// <summary>
        /// The <see cref="DependencyProperty"/> for <see cref="SelectedFile"/>.
        /// </summary>
        public static readonly DependencyProperty SelectedFileProperty =
            DependencyProperty.Register(
                SelectedFileName,
                typeof(FileInfo),
                typeof(ViewModel),
                new UIPropertyMetadata(null));
    
        /// <summary>
        /// The name of the <see cref="SelectedFile"/> <see cref="DependencyProperty"/>.
        /// </summary>
        public const string SelectedFileName = "SelectedFile";
    
        /// <summary>
        /// 
        /// </summary>
        public FileInfo SelectedFile
        {
            get { return (FileInfo)GetValue(SelectedFileProperty); }
            set { SetValue(SelectedFileProperty, value); }
        }
        #endregion
    
    
        /// <summary>
        /// The files found under <see cref="DirectoryName"/>.
        /// </summary>
        public ObservableCollection<FileInfo> Files { get; private set; }
    
        /// <summary>
        /// Holds the last filename error for IDataErrorInfo
        /// </summary>
        private string _lastDirectoryNameError = null;
        #endregion
    
        #region ctor
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewModel"/> class.
        /// </summary>
        public ViewModel()
        {
            Files = new ObservableCollection<FileInfo>();
        }
        #endregion
    
        #region methods
        /// <summary>
        /// Invoked whenever the effective value of any dependency property on this <see cref="T:System.Windows.DependencyObject"/> has been updated. The specific dependency property that changed is reported in the event data.
        /// </summary>
        /// <param name="e">Event data that will contain the dependency property identifier of interest, the property metadata for the type, and old and new values.</param>
        protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
        {
            base.OnPropertyChanged(e);
            if (e.Property == DirectoryNameProperty)
                UpdateFiles(e.OldValue as string, e.NewValue as string);
        }
    
        /// <summary>
        /// Updates <see cref="Files"/> when <see cref="DirectoryName"/> changes.
        /// </summary>
        /// <param name="oldDirectoryName">The old value of <see cref="DirectoryName"/></param>
        /// <param name="newDirectoryName">The new value of <see cref="DirectoryName"/></param>
        private void UpdateFiles(string oldDirectoryName, string newDirectoryName)
        {
            if (string.IsNullOrWhiteSpace(newDirectoryName))
            {
                Files.Clear();
                return;
            }
            if (!string.IsNullOrEmpty(oldDirectoryName) &&
                oldDirectoryName.Equals(newDirectoryName, StringComparison.OrdinalIgnoreCase))
                return;
    
            try
            {
                var di = new DirectoryInfo(Directory.Exists(newDirectoryName) ? newDirectoryName : Path.GetDirectoryName(newDirectoryName));
                // dirty hack
                if (di.ToString().Equals(".", StringComparison.OrdinalIgnoreCase))
                {
                    _lastDirectoryNameError = "Not a valid directory name.";
                    return;
                }
                Files.Clear();
                foreach (var file in di.GetFiles())
                    Files.Add(file);
                _lastDirectoryNameError = null;
            }
            catch (Exception ioe)
            {
                _lastDirectoryNameError = ioe.Message;
            }
        }
        #endregion
    
        #region IDataErrorInfo
        /// <summary>
        /// Gets an error message indicating what is wrong with this object.
        /// </summary>
        /// <returns>An error message indicating what is wrong with this object. The default is an empty string ("").</returns>
        string IDataErrorInfo.Error
        {
            get
            {
                return _lastDirectoryNameError;
            }
        }
    
        /// <summary>
        /// Gets the error message for the property with the given name.
        /// </summary>
        /// <returns>The error message for the property. The default is an empty string ("").</returns>
        string IDataErrorInfo.this[string columnName]
        {
            get
            {
                if (columnName.Equals(DirectoryNameName, StringComparison.OrdinalIgnoreCase))
                    return _lastDirectoryNameError;
                return null;
            }
        }
        #endregion
    }
    

    Next, open MainWindow.xaml and replace the xaml with the following:

    <Window
        x:Class="SimpleMVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:t="clr-namespace:SimpleMVVM"
        Title="MainWindow"
        Height="350"
        Width="525">
        <Window.DataContext>
            <t:ViewModel />
        </Window.DataContext>
        <Window.Resources>
            <Style
                x:Key="alternatingListViewItemStyle"
                TargetType="{x:Type ListViewItem}">
                <Style.Triggers>
                    <Trigger
                        Property="ItemsControl.AlternationIndex"
                        Value="1">
                        <Setter
                            Property="Background"
                            Value="LightGray"></Setter>
                    </Trigger>
                    <Trigger
                        Property="ItemsControl.AlternationIndex"
                        Value="2">
                        <Setter
                            Property="Background"
                            Value="White"></Setter>
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Window.Resources>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition
                    Height="auto" />
                <RowDefinition />
                <RowDefinition
                    Height="auto" />
            </Grid.RowDefinitions>
            <TextBox
                Margin="4"
                Text="{Binding DirectoryName, ValidatesOnDataErrors=True, ValidatesOnExceptions=True,UpdateSourceTrigger=PropertyChanged}">
                <TextBox.Style>
                    <Style
                        TargetType="TextBox">
                        <Setter
                            Property="ToolTip"
                            Value="Please enter a directory name" />
                        <Style.Triggers>
                            <Trigger
                                Property="Validation.HasError"
                                Value="true">
                                <Setter
                                    Property="ToolTip"
                                    Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}" />
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </TextBox.Style>
            </TextBox>
            <ListView
                Margin="4"
                Grid.Row="1"
                AlternationCount="2"
                ItemsSource="{Binding Files}"
                ItemContainerStyle="{StaticResource alternatingListViewItemStyle}"
                SelectedItem="{Binding SelectedFile}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition />
                                <RowDefinition />
                                <RowDefinition />
                                <RowDefinition />
                            </Grid.RowDefinitions>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition
                                    Width="100" />
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>
                            <Label
                                Grid.Row="0">Name</Label>
                            <Label
                                Grid.Row="1">Size</Label>
                            <Label
                                Grid.Row="2">Read Only</Label>
                            <Label
                                Grid.Row="3">Type</Label>
                            <TextBlock
                                Grid.Row="0"
                                Grid.Column="1"
                                Text="{Binding Name}" />
                            <TextBlock
                                Grid.Row="1"
                                Grid.Column="1"
                                Text="{Binding Length}" />
                            <CheckBox
                                Grid.Row="2"
                                Grid.Column="1"
                                IsChecked="{Binding IsReadOnly}"
                                IsEnabled="False" />
                            <TextBlock
                                Grid.Row="3"
                                Grid.Column="1"
                                Text="{Binding Extension}" />
                        </Grid>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <StatusBar
                Grid.Row="2">
                <StatusBarItem
                    Content="{Binding SelectedFile.FullName, StringFormat='Selected: {0}', FallbackValue='Please enter a directory and select a file.'}" />
            </StatusBar>
        </Grid>
    </Window>
    

    (excuse me everybody for the code dump!) Compile, fix errors and run it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Good Day, Can someone confirm what was said at the bottom of this post
good day dear php-fans at stackoverflow. i want to use imagegrabscreen — to get
Good day friends! I'm experiencing one huge problem here! First, I posted a question
Good day! I've found this solution here: VS2010 Web Publish command line version of
hello and good day dear xml-friends, i am new to xml so do not
hello and good day dear xml-friends, i am new to xml so do not
Good day, I try to start new Activity from another. But it always crashed.
Good day, all. I know that this is a pretty basic question in terms
Good day, to stackoverflow community. I have run into a bug with regard to
Good day everyone, this is one of those areas that is a little over

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.