How to select combobox item automatically and programatically? - c#

I have an array of combo boxes, and once each combo box is populated with items, I want the first item to be selected automatically. SO I do this:
all_transition_boxes[slide_item].SelectedItem = all_transition_boxes[slide_item].Items[0];
but then later I can not change the index anymore if I want to select some other item. It seems that the index is permanently set to zero. I tried to use SelectedItem instead of SelectedIndex but it doesn't work at all. I would appreciate any help.
//populate each combobox with corresponding elements
for (int i = 0; i < slide_transitions.Count; i++)
{
all_transition_boxes[slide_item].Items.Add("Transition " + (i + 1));
}
all_transition_boxes[slide_item].SelectedItem = all_transition_boxes[slide_item].Items[0];

I have created a sample code to replicate your issue, please check it.
A form with a combobox and two buttons:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" Activated="Window_Activated">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="329*"/>
<ColumnDefinition Width="34*"/>
<ColumnDefinition Width="154*"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="comboBox" HorizontalAlignment="Left" Margin="146,78,0,0" VerticalAlignment="Top" Width="120"/>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="101,185,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
<Button x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="266,185,0,0" VerticalAlignment="Top" Width="75" Grid.ColumnSpan="2" Click="button1_Click"/>
</Grid>
</Window>
And the formĀ“s code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Activated(object sender, EventArgs e)
{
var items = new List<string>();
for (var i = 0; i < 10; i++)
{
items.Add("Item" + i);
}
comboBox.ItemsSource = items;
comboBox.SelectedItem = "Item0";
}
private void button_Click(object sender, RoutedEventArgs e)
{
comboBox.SelectedItem = "Item5";
}
private void button1_Click(object sender, RoutedEventArgs e)
{
comboBox.SelectedItem = "Item9";
}
}
}

On your ComboBox (in XAML) set:
SelectedIndex = "0"
You can set it as a setter in a style that is applied to all instances of ComboBox in your array.

Related

Can't Access Button from drag n drop UI programatically

I created a new WPF app in Visual Studio and I placed a button using the drag and drop editor but I can't access the button in my .cs file using
MainButton.Content = "Set output to red";
but I get an error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
MainButton was null while running the application.
The drag and drop editor generated this xaml file
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Border HorizontalAlignment="Center" VerticalAlignment="Center" BorderBrush="Black" BorderThickness="3">
<TextBlock x:Name="Output" Background="Transparent" TextAlignment="Center" TextWrapping="Wrap" Text="Output" Height="88" Width="264"/>
</Border>
<RadioButton x:Name="Option1" Content="Red Pill" HorizontalAlignment="Left" Margin="135,75,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked" IsChecked="True"/>
<RadioButton x:Name="Option2" Content="Blue Pill" HorizontalAlignment="Left" Margin="536,72,0,0" VerticalAlignment="Top" Checked="RadioButton_Checked_1"/>
<Button x:Name="MainButton" Content="Set output to red" HorizontalAlignment="Left" Margin="279,100,0,0" VerticalAlignment="Top" Width="213" Height="41" Click="MainButton_Click"/>
</Grid>
</Window>
Here's the .cs file
using System.Windows;
using System.Windows.Media;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MainButton_Click(object sender, RoutedEventArgs e)
{
if ((bool)Option1.IsChecked)
{
Output.Background = Brushes.Crimson;
}
else
{
Option2.IsChecked = true;
Output.Background = Brushes.DodgerBlue;
}
}
private void RadioButton_Checked(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1(object sender, RoutedEventArgs e)
{
MainButton.Content = "Set output to blue";
}
}
}
I can access other things in the UI just fine like radio buttons and text blocks but not the button. Why could this be happening?
During the initialization phase, some variables are going to be null since it hasn't been reached in the call order. RadioButton_Checked is called through event before the button is constructed since it contains the Checked property.
A quick and easy fix is as follows: Check for null in your event calls.
private void RadioButton_Checked (object sender, RoutedEventArgs e)
{
if(MainButton != null)
MainButton.Content = "Set output to red";
}
private void RadioButton_Checked_1 (object sender, RoutedEventArgs e)
{
if (MainButton != null)
MainButton.Content = "Set output to blue";
}
Of course, there are better ways to handle this. You could set checked on a separate event, Initialized, which will handle it much cleaner.

WPF Need to find a way to identify TypeOf on custom Page class

I have a Window class called MainWindow, and in its constructor, builds a default Page class I call, MonitorPage that populates my window with this page at launch. In my MainWindow, I have three buttons that act as page tabs or menu buttons that upon clicking them will create an instance of a different Page class, in my case I have three unique pages. MonitorPage, DataBasePage, HelpPage. In my MainWindow, I want to "grey-out" the tab button when that corresponding page is up. I have a method in MainWindow called, PageState(), that tries to identify which page is currently up to enable or disable and grey out the tabs. My problem is that I get a NullReferenceException in my method at the first IF check.
The Error I'm Getting:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Controls.ContentControl.Content.get returned null.
C#:
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using System.Windows.Media;
namespace EyeInTheSky
{
/// <summary>
/// Interaction logic for MainWindow.xaml + backend code for FileSystemWatcher project
/// </summary>
public partial class MainWindow : Window
{
#region Fields
private FileSystemWatcher _watcher = new FileSystemWatcher();
private ObservableCollection<string[]> _eventList = new ObservableCollection<string[]>();
#endregion
public MainWindow()
{
InitializeComponent();
Main.Content = new MonitorPage(ref _watcher, ref _eventList);
PageState();
}
private void PageState()
{
if (Main.Content.GetType() == typeof(MonitorPage))
{
Menu_MonitorButton.IsEnabled = false;
Menu_MonitorButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
Menu_DataBaseButton.IsEnabled = true;
Menu_HelpButton.IsEnabled = true;
}
else if (Main.GetType() == typeof(DataBasePage))
{
Menu_MonitorButton.IsEnabled = true;
Menu_DataBaseButton.IsEnabled = false;
Menu_DataBaseButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
Menu_HelpButton.IsEnabled = true;
}
else
{
Menu_MonitorButton.IsEnabled = true;
Menu_DataBaseButton.IsEnabled = true;
Menu_HelpButton.IsEnabled = false;
Menu_HelpButton.Background = new SolidColorBrush(Color.FromRgb(88, 88, 95));
}
}
private void Menu_MonitorButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new MonitorPage(ref _watcher, ref _eventList);
}
private void MenuStrip_DataBaseButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new DataBasePage(ref _eventList);
}
private void MenuStrip_HelpButton_Click(object sender, RoutedEventArgs e)
{
PageState();
Main.Content = new HelpPage();
}
}
}
XAML:
<Window x:Name="Home" x:Class="EyeInTheSky.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:EyeInTheSky"
xmlns:System="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="Eye In The Sky - Windows File System Watcher" Height="450" Width="1105" WindowStartupLocation="CenterScreen" ResizeMode="NoResize" TextOptions.TextFormattingMode="Ideal" Background="#FF39393E" Foreground="#FFE4E4E4" FontFamily="Roboto">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="27*"/>
<RowDefinition Height="394*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="240*"/>
<ColumnDefinition Width="859*"/>
</Grid.ColumnDefinitions>
<Frame x:Name="Main" Height="421" VerticalAlignment="Top" Grid.RowSpan="2" Grid.ColumnSpan="2" Panel.ZIndex="1"/>
<DockPanel HorizontalAlignment="Left" Height="27" LastChildFill="False" VerticalAlignment="Top" Width="240" Panel.ZIndex="10000">
<StackPanel x:Name="Menu" Orientation="Horizontal" HorizontalAlignment="Left" Height="27" VerticalAlignment="Top" Width="240" Background="#FF4E4E53">
<Button x:Name="Menu_MonitorButton" Content="Monitor" Width="80" Click="Menu_MonitorButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" BorderThickness="1,0"/>
<Button x:Name="Menu_DataBaseButton" Content="Data Base" Width="80" Click="MenuStrip_DataBaseButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" BorderThickness="1,0"/>
<Button x:Name="Menu_HelpButton" Content="About" Width="80" Click="MenuStrip_HelpButton_Click" Background="#FF4E4E53" BorderBrush="#FF585858" Foreground="LightGray" Padding="0,1,1,1" BorderThickness="1,0,2,0"/>
</StackPanel>
</DockPanel>
</Grid>
</Window>

WPF NavigationService is null

I'm learning WPF (moving from Procedural PHP) and have written the following to navigate from 'MainWindow' to 'Page1', where there are no errors with the login credentials, but the local variable 'nav' is always null (hence displaying an error message):
namespace YM_POS_20160229_0949
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void ClickLoginSubmitButton(object sender, RoutedEventArgs e)
{
// Dictionary object is c# equivalent of PHP's 'array["key"] = "value"'
Dictionary<string, string> errMsg = new Dictionary<string, string>();
// declare variables
string varUserName;
string varUserPass;
// define the variables whilst trimming the values passed
varUserName = LoginUsername.Text.Trim();
varUserPass = LoginPassword.Password.Trim();
// ensure something has been submitted & perform validation on the values submitted
// if there are no errors, navigate to the users dashboard (aka Page1)
NavigationService nav = NavigationService.GetNavigationService(new Page1());
// check if the nav variable is populated
if (nav != null)
{
nav.Navigate(nav);
}
else
{
// display an error message to the user advising them an error has occurred and Page1 is not available
MessageBox.Show("An error has occured. unable to proceed to " + nav);
}
}
}
}
Any help greatly appreciated.
Thanks
Newbie Matt
//UI / XAML
<Window x:Class="YM_POS_20160229_0949.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:YM_POS_20160229_0949"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="123*"/>
<ColumnDefinition Width="394*"/>
</Grid.ColumnDefinitions>
<TextBox x:Name="LoginUsername" HorizontalAlignment="Left" Height="23" Margin="56.649,55,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" Grid.Column="1"/>
<PasswordBox x:Name="LoginPassword" HorizontalAlignment="Left" Height="23" Margin="56.649,100,0,0" Password="Password" VerticalAlignment="Top" Width="120" Grid.Column="1" />
<Button x:Name="LoginSubmitButton" Content="Submit" HorizontalAlignment="Left" Margin="81.649,172,0,0" VerticalAlignment="Top" Width="75" Click="ClickLoginSubmitButton" Grid.Column="1"/>
</Grid>
</DockPanel>
</Window>

WPF Binding control to another control

I have the following WPF window. Changing the value of #Cables adds (or removes) tabs to the TabControl (C2, C3, C4...). Changing #Phases adds new rows to the DataGrid.
All of the tabs (other than this Options one) have the same format, so I created a UserControl NTab class which has its own .xaml and code-behind.
Now, each of the other tabs will have a ComboBox, where the user selects the appropriate Phase (by the name property). For that to be possible, the NTab needs to be aware of the Phase DatGrid in the Options tab. My code is currently split into two classes:
MainWindow, which contains the code (.xaml and code-behind) for the window as a whole and for the Options Tab;
NTab, which contains the code (.xaml and code-behind) for itself.
The Phase DataGrid's ItemSource is an ObservableCollection, so what I've done is sent the collection to the NTab constructor and tied its .CollectionChanged event to the following NTab function (Phases is an ObservableCollection<string> dependency property):
public void PhasesChanged(object source, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
var pC = source as ObservableCollection<NPhase>;
Phases.Clear();
for (int i = 0; i < pC.Count; i++)
Phases.Add("" + (i + 1));
}
This creates a copy of the DataGrid's data (just the names) and stores it inside each NTab as a dependency property bound to the ComboBox. This works.
My question is if there is a better way to do this. I would rather not have to create "redundant" copies of data and would like to be able to bind the ComboBoxes directly to the DataGrid. Is this possible?
EDIT: Adding my code. I've deleted parts of the .xaml and code-behind which weren't relevant to the question.
MainWindow.xaml
<Window x:Class="WPF.MainWindow"
x:Name="Main"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:l="clr-namespace:WPF"
Title="WPF" SizeToContent="WidthAndHeight">
<TabControl Name="tabControl" SelectedIndex="1">
<TabItem Name="Options">
<TabItem.Header>
<TextBlock>Options</TextBlock>
</TabItem.Header>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<!-- ... -->
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.ColumnDefinitions>
<!-- ... -->
</Grid.ColumnDefinitions>
<Label Grid.Column="0"># Cables</Label>
<xctk:IntegerUpDown Name="nCables"
Grid.Column="1"
Minimum="1"
Value="1"
ValueChanged="nCablesChanged"/>
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<!-- ... -->
</Grid.ColumnDefinitions>
<Label Grid.Column="0"># Phases</Label>
<xctk:IntegerUpDown Name="nPhases"
Grid.Column="1"
Minimum="1"
Value="4"
ValueChanged="nPhasesChanged"/>
</Grid>
<l:NDataGrid Grid.Row="2"
x:Name="PhaseGrid"
ItemsSource="{Binding Phases, ElementName=Main}"
LoadingRow="RowIndex"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
VerticalScrollBarVisibility="Hidden"
Block.TextAlignment="Center"/>
</Grid>
</TabItem>
</TabControl>
</Window>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
ObservableCollection<NPhase> Phases;
public static DependencyProperty PhasesProperty = DependencyProperty.Register("Phases", typeof(ICollectionView), typeof(MainWindow));
public ICollectionView IPhasesCollection
{
get { return (ICollectionView)GetValue(PhasesProperty); }
set { SetValue(PhasesProperty, value); }
}
/// <summary>Controls the number of cables to be created</summary>
/// <param name="sender">(IntegerUpDown)nCables</param>
/// <param name="e">not used</param>
private void nCablesChanged(object sender, RoutedEventArgs e)
{
int n = tabControl.Items.Count - 1;
var o = sender as IntegerUpDown;
int v = (int)o.Value;
if (v > n)
{
for (int i = n; i < v; i++)
{
TabItem tab = new TabItem();
tab.Header = "C" + (i + 1);
tab.Content = new NTab(Phases);
tabControl.Items.Add(tab);
}
}
else if (v < n)
{
for (int i = v; i < n; i++)
tabControl.Items.RemoveAt(n);
}
}
/// <summary>Modifies the DataGrid according to the number of phases desired</summary>
/// <param name="sender">(IntegerUpDown)nPhases</param>
/// <param name="e">not used</param>
private void nPhasesChanged(object sender, RoutedEventArgs e)
{
//...
}
/// <summary>Sets up the row headers</summary>
/// <param name="sender">not used</param>
/// <param name="e">Row to be modified</param>
private void RowIndex(object sender, DataGridRowEventArgs e)
{
e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}
public MainWindow()
{
Phases = new ObservableCollection<NPhase>();
Phases.Add(new NPhase(3, "Protensao Inicial"));
Phases.Add(new NPhase(28, "Carga Movel"));
Phases.Add(new NPhase(365, "1 Ano"));
Phases.Add(new NPhase(18250, "Vida Util"));
IPhasesCollection = CollectionViewSource.GetDefaultView(Phases);
InitializeComponent();
}
}
NTab.xaml
<UserControl x:Class="WPF.NTab"
x:Name="CableTab"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:charting="clr-namespace:System.Windows.Forms.DataVisualization.Charting;assembly=System.Windows.Forms.DataVisualization"
xmlns:xctk="http://schemas.xceed.com/wpf/xaml/toolkit"
xmlns:l="clr-namespace:WPF"
mc:Ignorable="d" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<!-- ... -->
</Grid.RowDefinitions>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<!-- ... -->
</Grid.ColumnDefinitions>
<Label Grid.Column="2">Pull Phase</Label>
<ComboBox Grid.Column="3"
Name="Phase"
ItemsSource="{Binding Phases, ElementName=CableTab}"/>
</Grid>
</Grid>
</UserControl>
NTab.xaml.cs
public partial class NTab : UserControl
{
ObservableCollection<string> Phases;
public static DependencyProperty PhasesProperty = DependencyProperty.Register("Phases", typeof(ICollectionView), typeof(NTab));
public ICollectionView IPhasesCollection
{
get { return (ICollectionView)GetValue(PhasesProperty); }
set { SetValue(PhasesProperty, value); }
}
/// <summary>Updates the tab's Phase list to match the list in the Options tab.</summary>
/// <param name="source">(ObservableCollection<NPhase></param>
/// <param name="e">not used.</param>
public void PhasesChanged(object source, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
var pC = source as ObservableCollection<NPhase>;
Phases.Clear();
for (int i = 0; i < pC.Count; i++)
Phases.Add("" + (i + 1));
}
public NTab(ObservableCollection<NPhase> p)
{
InitializeComponent();
Phases = new ObservableCollection<string>();
IPhasesCollection = CollectionViewSource.GetDefaultView(Phases);
PhasesChanged(p, new System.Collections.Specialized.NotifyCollectionChangedEventArgs(System.Collections.Specialized.NotifyCollectionChangedAction.Reset));
p.CollectionChanged += PhasesChanged;
}
}
You're looking at this in the wrong way... it is a rare situation in WPF when a UI control needs to know anything about another UI control. It is much more common to work with the data. By this, I mean that your NTab only needs to be aware of the data from the Phase DataGrid and not the control.
The simplest way to achieve this is to have one view model for the whole TabControl which shares its properties over the various TabItems. So rather than trying to handle UI events to keep the collections the same, just use one collection for all of the TabItems. In the DataGrid, you could do this:
<DataGrid ItemsSource="{Binding YourCollection}" ... />
On each additional TabItem, you could have this:
<ComboBox ItemsSource="{Binding YourCollection}" ... />
In this way, an update to the collection in one TabItem will automatically be reflected in all of the other TabItems, without you having to do anything.

Dynamically preventing a TextBox from getting focus

I have a System.Windows.Controls.TextBox which I would like to behave as follows: When you click it, it is determined dynamically if the TextBox gets focus or not. Here's a toy application which contains a failed attempt at accomplishing this:
<!-- MainWindow.xaml -->
<Window x:Class="Focus.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Label Name="myLabel" Grid.Row="0" Background="Red"></Label>
<TextBox Name="myTextbox" Grid.Row="1" Background="Green"></TextBox>
</Grid>
</Window>
// MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Input;
namespace Focus
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
}
private static readonly Random myRandom = new Random();
private void myTextbox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
int randomInt = myRandom.Next(0, 2); // 0 or 1
myLabel.Content = randomInt;
if(randomInt==0)
{
// PREVENT FOCUS - INSERT CODE HERE. (The line below is a failed attempt.)
FocusManager.SetFocusedElement(this, myLabel);
}
}
}
}
The following code seems to do the trick:
// PREVENT FOCUS - INSERT CODE HERE.
myLabel.Focusable = true;
myLabel.Focus();
myLabel.Focusable = false;
I also changed this line of code:
myTextbox.PreviewGotKeyboardFocus += myTextbox_GotKeyboardFocus;
into this:
myTextbox.GotFocus += myTextbox_GotKeyboardFocus;
I hope you know that you hooked up to the keyboard focus (TAB key).
void textBox1_GotFocus(object sender, System.EventArgs e)
{
if (!this.checkBox1.Checked)
this.checkBox1.Focus();
else
this.textBox1.Focus();
}

Categories

Resources