How to resolve my apps design issues and app crashing?

don bradman 621 Reputation points
2022-03-06T16:11:40.5+00:00

In my WPF app why isn't the horizontal scroll bar showing or working properly?

XAML code:

https://codeshare.io/K8vDr8

CodeBehind:

    using System.ComponentModel;  
    using OfficeOpenXml;  
    using System.Data;  
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Windows;  
    using System.Windows.Controls;  
    using System.Windows.Data;  
    using System.Windows.Documents;  
    using System.Windows.Input;  
    using System.Windows.Media;  
      
    namespace mar22Proj  
    {  
    	public partial class Window1 : Window  
    	{  
    		private List<string> cBItems = new List<string>();  
      
    		List<string> Names = new List<string>();  
      
    		private ICollectionView view;  
      
      
    		string file_Bills = @"test.xlsx";  
      
    		private DataTable SelectExcelRows(string filename, string key)  
    		{  
    			using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(filename), false))  
    			{  
    				ExcelWorksheet workSheet = package.Workbook.Worksheets[0];  
      
    				DataTable dtTemp = new DataTable();  
    				dtTemp.Columns.Add("Party");  
    				dtTemp.Columns.Add("Bill No.");  
    				dtTemp.Columns.Add("Bill Date");  
    				dtTemp.Columns.Add("Amount");  
    				dtTemp.Columns.Add("Due Date");  
    				dtTemp.Columns.Add("Remarks");  
    				dtTemp.Columns.Add("Payment Released on");  
      
    				for (int row = 2; row <= workSheet.Dimension.End.Row; row++)  
    				{  
    					if (String.Equals(workSheet.Cells[row, 1].Text, key, StringComparison.OrdinalIgnoreCase))  
    						FilterDGV(dtTemp, workSheet, row);  
    				};  
      
    				return dtTemp;  
    			};  
    		}  
      
    		private static void FilterDGV(DataTable tbl, ExcelWorksheet sht, int rowIndex)  
    		{  
    			var drAddItem = tbl.NewRow();  
    			tbl.Rows.Add(drAddItem);  
      
    			foreach (var column in tbl.Columns.OfType<DataColumn>())  
    			{  
    				drAddItem[column] = sht.Cells[rowIndex, column.Ordinal+1].Text;  
    			};  
    		}  
    		  
    		public static string LastRow(string fpath)  
    		{  
    			using (ExcelPackage excelPackage = new ExcelPackage(fpath))  
    			{  
      
    				ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.First();  
      
    				int lastRow = 0;  
      
    				for (int i = 2; i <= worksheet.Dimension.End.Row; i++)  
    				{  
    					if (!string.IsNullOrEmpty(worksheet.Cells["A"+i].Text))  
    					{  
    						lastRow =i;  
    					}  
    				}  
    				return lastRow.ToString();  
    			}  
    		}  
    		  
    		public Window1()  
    		{  
    			InitializeComponent();  
    			ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;  
    			  
    			using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(file_Bills), false))  
    			{  
    				ExcelWorksheet mainSheet = package.Workbook.Worksheets.First();  
      
    				List<string> party = new List<string>();  
      
    				for (int row = 2; row <= Convert.ToInt32(LastRow(file_Bills)); row++)  
    				{  
    					if (!string.IsNullOrEmpty(mainSheet.Cells[row, 1].Text))  
    					{  
    						party.Add(mainSheet.Cells[row, 1].Text);  
    					}  
    				}  
      
      
    				foreach (var element in party.Distinct())  
    				{  
    					cBItems.Add(element);  
    				}  
      
    			}  
    			  
    			cmb.ItemsSource = cBItems;  
    			  
    			KeyboardNavigation.SetDirectionalNavigation(cmb, KeyboardNavigationMode.Cycle);  
    			view = CollectionViewSource.GetDefaultView(cBItems);  
      
    			rb1.IsChecked = true;  
    		}  
    		void window1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    		{  
    			DragMove();  
    		}  
    		void quit_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    		{  
    			Close();  
    		}  
    		void cmb_KeyUp(object sender, KeyEventArgs e)  
    		{  
    			var tb = cmb.Template.FindName("PART_EditableTextBox", cmb) as System.Windows.Controls.TextBox;  
    			var val = tb.Text;  
    			var empty = string.IsNullOrEmpty(tb.Text);  
      
    			var keysToIgnore = new Key[] { Key.Down, Key.Up, Key.Enter, Key.Left, Key.Right };  
      
    			if (keysToIgnore.Contains(e.Key))  
    			{  
    				return;  
    			}  
      
    			if (empty)  
    			{  
    				view.Filter = null;  
    			}  
    			else  
    			{  
    				view.Filter = (i) =>  
    				{  
    					var str = i.ToString();  
    					return str.ToLowerInvariant().Contains(tb.Text.ToLowerInvariant());  
    				};  
    			}  
      
    			cmb.IsDropDownOpen = true;  
      
    			tb.Text = val;  
    			tb.CaretIndex = tb.Text.Length;  
    		}  
    		void cmb_SelectionChanged(object sender, SelectionChangedEventArgs e)  
    		{  
    			var results = SelectExcelRows(file_Bills, (sender as System.Windows.Controls.ComboBox).SelectedItem as string);  
      
    			dg.ItemsSource = results.DefaultView;  
    		}  
    		void maximize_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
    		{  
    			if (WindowState==WindowState.Normal)  
    			{  
    				WindowState=WindowState.Maximized;  
    			}  
    			else  
    				WindowState=WindowState.Normal;  
    		}  
    		void rb1_Checked(object sender, RoutedEventArgs e)  
    		{  
    			txt.Text="";  
    			txt.Focus();  
    			tblock.Text = "Enter full invoice number or a part of it";  
    		}  
    		void rb2_Checked(object sender, RoutedEventArgs e)  
    		{  
    			txt.Text="";  
    			txt.Focus();  
    			tblock.Text = "Enter a complete date (day, then month and then year)";  
    		}  
    		void rb3_Checked(object sender, RoutedEventArgs e)  
    		{  
    			txt.Text="";  
    			txt.Focus();  
    			tblock.Text = "Enter exact amount as per Invoice";  
    		}  
    		void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)  
    		{  
    			e.Column = new DataGridTextColumn() {  
    				Header = e.PropertyName,  
    				SortMemberPath = e.PropertyName, //To allow for sorting on a column  
    				Binding = new Binding("[" + e.PropertyName + "]")  
    			};  
    		}  
    	}  
    }  

Also, when I try to type in the combo box the app crashes. How do I fix that as well?180387-mar22proj-2022-03-06-21-55-28.gif

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,671 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,238 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
762 questions
{count} votes

Accepted answer
  1. Hui Liu-MSFT 38,251 Reputation points Microsoft Vendor
    2022-03-08T05:39:34.36+00:00

    I'm not sure what you are trying to achieve here, the error should be that the view is not instantiated. You could try to instantiate the view as needed.

    180883-image.png

    I put the code List<string> party = new List<string>(); outside the method and try to add code like below .

    void cmb_KeyUp(object sender, KeyEventArgs e)  
                {  
                    var tb = cmb.Template.FindName("PART_EditableTextBox", cmb) as TextBox;  
                    var val = tb.Text;  
                    var empty = string.IsNullOrEmpty(tb.Text);  
                    var keysToIgnore = new Key[] { Key.Down, Key.Up, Key.Enter, Key.Left, Key.Right };  
                    if (keysToIgnore.Contains(e.Key))  
                    {  
                      return;  
                    }  
                    if (empty)  
                    {  
                    view.Filter = null;  
                    }  
                    else  
                    {  
                        view = CollectionViewSource.GetDefaultView(party);  
                        view.Filter = (i) =>  
                        {  
                            var str = i.ToString();  
                            return str.ToLowerInvariant().Contains(tb.Text.ToLowerInvariant());  
                        };  
                    }  
                    cmb.IsDropDownOpen = true;  
                    tb.Text = val;  
                 //tb.CaretIndex = tb.Text.Length;  
                }  
    

    Update:

     <Style  
     TargetType="{x:Type DataGrid}">  
                <Setter Property="ColumnWidth"  Value="auto"></Setter>  
                <Setter Property="FontSize" Value="13"></Setter>  
            </Style>  
    

    You could modify your dg_AutoGeneratingColumn method as needed.

    void dg_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)  
                {  
                    string headerName = e.Column.Header.ToString();  
                e.Column = new DataGridTextColumn()  
                {  
                    Header = e.PropertyName,  
                     
                    SortMemberPath = e.PropertyName, //To allow for sorting on a column  
                    Binding = new Binding("[" + e.PropertyName + "]")  
                    };  
                    if (headerName == "Party")  
                    {  
                    e.Column.Width = 298;  
                    }  
                //if (headerName == "Bill No.")  
                //{  
                //e.Column.Width = 148;  
                //}  
      
                if (headerName == "Bill Date")  
                {  
                    e.Column.Width = 148;  
                }  
                //if (headerName == "Amount")  
                //{  
                //e.Column.Width = 148;  
                //}  
                if (headerName == "Due Date")  
                    {  
                    e.Column.Width = 248;  
                    }  
                    if (headerName == "Remarks")  
                    {  
                    e.Column.Width = 248;  
                    }  
                    if (headerName == "Payment Released on")  
                    {  
                    e.Column.Width = 288;  
                    }  
                }  
    

    181356-image.png

    Update 2 : You can add additional properties to Combobox to filter.

     <ComboBox	IsTextSearchEnabled="True"	IsReadOnly="False" 	IsEditable="True"	Margin="10,0"	x:Name="cmb"	Width="380"  
    				Height="35"		HorizontalAlignment="Left"	VerticalAlignment="Top"		SelectionChanged="cmb_SelectionChanged"   KeyUp="cmb_KeyUp"    
                         local:ComboBox.IsFilterOnAutocompleteEnabled="True" />  
    
    
     class ComboBox : DependencyObject  
      {  
        #region IsFilterOnAutoCompleteEnabled attached property  
      
        public static readonly DependencyProperty IsFilterOnAutocompleteEnabledProperty =  
          DependencyProperty.RegisterAttached(  
            "IsFilterOnAutocompleteEnabled",  
            typeof(bool),  
            typeof(ComboBox),  
            new PropertyMetadata(default(bool), ComboBox.OnIsFilterOnAutocompleteEnabledChanged));  
      
        public static void SetIsFilterOnAutocompleteEnabled(DependencyObject attachingElement, bool value) =>  
          attachingElement.SetValue(ComboBox.IsFilterOnAutocompleteEnabledProperty, value);  
      
        public static bool GetIsFilterOnAutocompleteEnabled(DependencyObject attachingElement) =>  
          (bool)attachingElement.GetValue(ComboBox.IsFilterOnAutocompleteEnabledProperty);  
      
        #endregion  
      
        private static Dictionary<TextBox, System.Windows.Controls.ComboBox> TextBoxComboBoxMap { get; }  
        private static Dictionary<TextBox, int> TextBoxSelectionStartMap { get; }  
        private static Dictionary<System.Windows.Controls.ComboBox, TextBox> ComboBoxTextBoxMap { get; }  
        private static bool IsNavigationKeyPressed { get; set; }  
      
        static ComboBox()  
        {  
          ComboBox.TextBoxComboBoxMap = new Dictionary<TextBox, System.Windows.Controls.ComboBox>();  
          ComboBox.TextBoxSelectionStartMap = new Dictionary<TextBox, int>();  
          ComboBox.ComboBoxTextBoxMap = new Dictionary<System.Windows.Controls.ComboBox, TextBox>();  
        }  
        private static void OnIsFilterOnAutocompleteEnabledChanged(  
          DependencyObject attachingElement,  
          DependencyPropertyChangedEventArgs e)  
        {  
          if (!(attachingElement is System.Windows.Controls.ComboBox comboBox  
            && comboBox.IsEditable))  
          {  
            return;  
          }  
          if (!(bool)e.NewValue)  
          {  
            ComboBox.DisableAutocompleteFilter(comboBox);  
            return;  
          }  
      
          if (!comboBox.IsLoaded)  
          {  
            comboBox.Loaded += ComboBox.EnableAutocompleteFilterOnComboBoxLoaded;  
            return;  
          }  
          ComboBox.EnableAutocompleteFilter(comboBox);  
        }  
        private static async void FilterOnTextInput(object sender, TextChangedEventArgs e)  
        {  
          await Application.Current.Dispatcher.InvokeAsync(  
            () =>  
            {  
              if (ComboBox.IsNavigationKeyPressed)  
              {  
                return;  
              }  
              var textBox = sender as TextBox;  
              int textBoxSelectionStart = textBox.SelectionStart;  
              ComboBox.TextBoxSelectionStartMap[textBox] = textBoxSelectionStart;  
      
              string changedTextOnAutocomplete = textBox.Text.Substring(0, textBoxSelectionStart);  
              if (ComboBox.TextBoxComboBoxMap.TryGetValue(  
                textBox,  
                out System.Windows.Controls.ComboBox comboBox))  
              {  
                comboBox.Items.Filter = item => item.ToString().StartsWith(  
                  changedTextOnAutocomplete,  
                  StringComparison.OrdinalIgnoreCase);  
              }  
            },  
            DispatcherPriority.Background);  
        }  
        private static async void HandleKeyDownWhileFiltering(object sender, KeyEventArgs e)  
        {  
          var comboBox = sender as System.Windows.Controls.ComboBox;  
          if (!ComboBox.ComboBoxTextBoxMap.TryGetValue(comboBox, out TextBox textBox))  
          {  
            return;  
          }  
          switch (e.Key)  
          {  
            case Key.Down  
              when comboBox.Items.CurrentPosition < comboBox.Items.Count - 1  
                   && comboBox.Items.MoveCurrentToNext():  
            case Key.Up  
              when comboBox.Items.CurrentPosition > 0  
                   && comboBox.Items.MoveCurrentToPrevious():  
              {  
                ComboBox.IsNavigationKeyPressed = true;  
                await Application.Current.Dispatcher.InvokeAsync(  
                  () =>  
                  {  
                    ComboBox.SelectCurrentItem(textBox, comboBox);  
                    ComboBox.IsNavigationKeyPressed = false;  
                  },  
                  DispatcherPriority.ContextIdle);  
                break;  
              }  
          }  
        }  
        private static void SelectCurrentItem(TextBox textBox, System.Windows.Controls.ComboBox comboBox)  
        {  
          comboBox.SelectedItem = comboBox.Items.CurrentItem;  
          if (ComboBox.TextBoxSelectionStartMap.TryGetValue(textBox, out int selectionStart))  
          {  
            textBox.SelectionStart = selectionStart;  
          }  
        }  
        private static void EnableAutocompleteFilterOnComboBoxLoaded(object sender, RoutedEventArgs e)  
        {  
          var comboBox = sender as System.Windows.Controls.ComboBox;  
          ComboBox.EnableAutocompleteFilter(comboBox);  
        }  
      
        private static void EnableAutocompleteFilter(System.Windows.Controls.ComboBox comboBox)  
        {  
          if (comboBox.TryFindVisualChildElement(out TextBox editTextBox))  
          {  
            ComboBox.TextBoxComboBoxMap.Add(editTextBox, comboBox);  
            ComboBox.ComboBoxTextBoxMap.Add(comboBox, editTextBox);  
            editTextBox.TextChanged += ComboBox.FilterOnTextInput;  
      
            comboBox.AddHandler(UIElement.PreviewKeyDownEvent, new KeyEventHandler(HandleKeyDownWhileFiltering), true);  
          }  
        }  
        private static void DisableAutocompleteFilter(System.Windows.Controls.ComboBox comboBox)  
        {  
          if (comboBox.TryFindVisualChildElement(out TextBox editTextBox))  
          {  
            ComboBox.TextBoxComboBoxMap.Remove(editTextBox);  
            editTextBox.TextChanged -= ComboBox.FilterOnTextInput;  
          }  
        }  
      }  
      public static class Extensions  
      {  
        public static bool TryFindVisualChildElement<TChild>(this DependencyObject parent, out TChild resultElement)  
          where TChild : DependencyObject  
        {  
          resultElement = null;  
      
          if (parent is Popup popup)  
          {  
            parent = popup.Child;  
            if (parent == null)  
            {  
              return false;  
            }  
          }  
          for (var childIndex = 0; childIndex < VisualTreeHelper.GetChildrenCount(parent); childIndex++)  
          {  
            DependencyObject childElement = VisualTreeHelper.GetChild(parent, childIndex);  
            if (childElement is TChild child)  
            {  
              resultElement = child;  
              return true;  
            }  
      
            if (childElement.TryFindVisualChildElement(out resultElement))  
            {  
              return true;  
            }  
          }  
          return false;  
        }  
      }  
    

    The result:
    181881-9.gif


    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful