App crashes the first time I select an item in a combobox defined programmatically in a grid that is added as a child of a stack panel - combobox

I get the following error on a Zebra tablet t55 when running my app:
Unhandled exception at 0x00007FFEA4A22D45 (Windows.UI.Xaml.dll) in PerfectDelivery.exe: 0xC000041D: An unhandled exception was encountered during a user callback.
It happens after I load all my sqlite database and run the app the first time. After the crash I start the app back up again and it runs fine. The offending Combobox is here:
private void InitProducts()
{
StpProducts.Children.Clear();
_lstItemsInMultipleCrates = new List<int>();
Invoice deliveryDetails = new Invoice(((App)Application.Current).OrderId);
ItemsInCrate = new List<InvoiceItem>();
if (_selectedCrate != null)
{
btnFinishCrate.Visibility = Visibility.Visible;
foreach (InvoiceItem i in deliveryDetails.InvoiceItems.Where(
x => x.CrateNumber.CrateId == _selectedCrate))
{
ItemsInCrate.Add(i);
GridProducts = new Grid();
GridProducts.Height = 35;
GridProducts.Width = 600;
GridProducts.HorizontalAlignment = HorizontalAlignment.Left;
ColumnDefinition cdProductName = new ColumnDefinition();
cdProductName.Width = new GridLength(170, GridUnitType.Star);
ColumnDefinition cdQty = new ColumnDefinition();
cdQty.Width = new GridLength(45, GridUnitType.Star);
ColumnDefinition cdUnits = new ColumnDefinition();
cdUnits.Width = new GridLength(60, GridUnitType.Star);
ColumnDefinition cdChecked = new ColumnDefinition();
cdChecked.Width = new GridLength(30, GridUnitType.Star);
ColumnDefinition cdDropdown = new ColumnDefinition();
cdDropdown.Width = new GridLength(80, GridUnitType.Star);
ColumnDefinition cdFiller = new ColumnDefinition();
cdFiller.Width = new GridLength(1, GridUnitType.Star);
RowDefinition row = new RowDefinition();
row.Height = new GridLength(35, GridUnitType.Star);
GridProducts.ColumnDefinitions.Add(cdProductName);
GridProducts.ColumnDefinitions.Add(cdQty);
GridProducts.ColumnDefinitions.Add(cdUnits);
GridProducts.ColumnDefinitions.Add(cdChecked);
GridProducts.ColumnDefinitions.Add(cdDropdown);
TextBlock txbOrderDetailPickedId = new TextBlock { Name = "ODPID" };
txbOrderDetailPickedId.Text = i.OrderDetailPickedId.ToString("G");
txbOrderDetailPickedId.Visibility = Visibility.Collapsed;
TextBlock txbOriginalQty = new TextBlock { Name = "OQ" };
txbOriginalQty.Text = i.Quantity.ToString("N");
txbOriginalQty.Visibility = Visibility.Collapsed;
List<long?> lstCrateCount = new List<long?>();
foreach (InvoiceItem crateCount in deliveryDetails.InvoiceItems.Where(x => x.CrateNumber.OrderDetailPickedId == i.OrderDetailPickedId))
{
lstCrateCount.Add(crateCount.CrateNumber.CrateId);
}// return count of crates for item. If > 1 display crate number(s)
TextBlock txbProductName = new TextBlock();
TextBox txbQuantity = new TextBox();
txbQuantity.Text = i.Quantity.ToString("N");
txbQuantity.Height = 35;
InputScope scope = new InputScope();
InputScopeName scopeName = new InputScopeName { NameValue = InputScopeNameValue.Number };
scope.Names.Add(scopeName);
txbQuantity.InputScope = scope;
TextBlock txbUnits = new TextBlock();
txbUnits.Text = i.PackDescription;
txbUnits.HorizontalTextAlignment = TextAlignment.Center;
txbUnits.VerticalAlignment = VerticalAlignment.Center;
CheckBox chkChecked = new CheckBox();
---> CmbDiscrepancies = new ComboBox{ SelectedIndex = -1};
if (CmbDiscrepancies?.Items != null)
{
CmbDiscrepancies.Items.Add("Correct");
CmbDiscrepancies.Items.Add("Damaged");
CmbDiscrepancies.Items.Add("Missing");
CmbDiscrepancies.Items.Add("Wrong Item");
CmbDiscrepancies.Items.Add("Out of Stock");
CmbDiscrepancies.Items.Add("Incorrect Amt");
}
CmbDiscrepancies.SelectedIndex = 0;
CmbDiscrepancies.VerticalAlignment = VerticalAlignment.Center;*
if (lstCrateCount.Count == 1)
{
txbProductName.Text = i.ProductName;
}
else if (!Crate.ItemInMultipleCrates(i.OrderDetailPickedId))
{
_lstItemsInMultipleCrates.Add(i.OrderDetailPickedId);
txbProductName.TextWrapping = TextWrapping.Wrap;
txbProductName.Text = i.ProductName + "\r\n" + "(";
int count = 0;
foreach (long? crate in lstCrateCount)
{
count++;
txbProductName.Text += count != lstCrateCount.Count ? crate + ", " : crate + ")\r\nQty is the total in all crates listed above.";
}
GridProducts.Height = 50 * (lstCrateCount.Count * .66);
row.Height = new GridLength(GridProducts.Height, GridUnitType.Pixel);
}
if (Crate.ItemInMultipleCrates(i.OrderDetailPickedId))
{
txbProductName.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
CmbDiscrepancies.IsEnabled = false;
txbQuantity.IsEnabled = false;
if (_lstItemsInMultipleCrates.Count > 0)
GridProducts.Height = 35 * (_lstItemsInMultipleCrates.Count * 1.32);
else
{
GridProducts.Height = 35 * 1.32;
}
row.Height = new GridLength(GridProducts.Height, GridUnitType.Pixel);
txbProductName.Text = i.ProductName + "\r\n" + "(Item is in multiple crates)";
chkChecked.IsChecked = true;
chkChecked.IsEnabled = false;
}
GridProducts.Children.Add(txbOriginalQty);
GridProducts.Children.Add(txbOrderDetailPickedId);
GridProducts.Children.Add(txbProductName);
GridProducts.Children.Add(txbQuantity);
GridProducts.Children.Add(txbUnits);
GridProducts.Children.Add(chkChecked);
GridProducts.Children.Add(CmbDiscrepancies);
Grid.SetColumn(txbProductName, 0);
Grid.SetColumn(txbQuantity, 1);
Grid.SetColumn(txbUnits, 2);
Grid.SetColumn(chkChecked, 3);
Grid.SetColumn(CmbDiscrepancies, 4);
Grid.SetRow(txbProductName, 0);
Grid.SetRow(txbQuantity, 0);
Grid.SetRow(txbUnits, 0);
Grid.SetRow(chkChecked, 0);
Grid.SetRow(CmbDiscrepancies, 0);
GridProducts.RowDefinitions.Add(row);
StpProducts.Children.Add(GridProducts);
}
}
The XAML is
<ScrollViewer x:Name="ScvProducts" HorizontalAlignment="Left" Height="354" Margin="375,146,0,0" VerticalAlignment="Top" Width="638" BorderBrush="#FF1B933C" BorderThickness="2" >
<StackPanel x:Name="StpProducts" MinHeight="450" Width="612" HorizontalAlignment="Left" VerticalAlignment="Top" Orientation="Vertical" Height="995" >
<Grid x:Name="GridProducts">
<ComboBox x:Name="CmbDiscrepancies" Visibility></ComboBox>
</Grid>
</StackPanel>
</ScrollViewer>

Upgrading from Windows 10 1709 to 1803 fixed the existing code. I also got rid of the stack panel and add the row definitions dynamically which seems to have addressed the 1709 version.

Related

How to set constraints in WinForm?

I created UserControl and put there a two GroupBox one at the top and one at the bottom... there is a screenshot
And then when I put this UserControl with my a views within to TabController I got such a result
So, as you see in the main form it looks like it is not enough space for all views within UserControl
Question is - is there a way to set that GroupBox at the top will take 50% of the height and GroupBox at the bottom will take also 50% of the height, such way this two GroupBox view will take 100% of the height each for 50%...
alternatively use TableLayoutPanel with two rows (each row gets 50% height)
private void InitializeComponent()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
this.tableLayoutPanel1.Controls.Add(this.groupBox1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.groupBox2, 0, 2);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 3);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 4F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(507, 408);
this.tableLayoutPanel1.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(3, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(501, 196);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "groupBox1";
//
// groupBox2
//
this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox2.Location = new System.Drawing.Point(3, 209);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(501, 196);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "groupBox2";
//
// Form3
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(513, 414);
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "Form3";
this.Padding = new System.Windows.Forms.Padding(3);
this.Text = "Form3";
this.tableLayoutPanel1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;
you can use SplitContainer (IsSplitterFixed = true; will not allow to change proportions)
private void InitializeComponent()
{
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.IsSplitterFixed = true;
this.splitContainer1.Location = new System.Drawing.Point(3, 3);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.groupBox1);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.groupBox2);
this.splitContainer1.Size = new System.Drawing.Size(459, 395);
this.splitContainer1.SplitterDistance = 197;
this.splitContainer1.SplitterWidth = 1;
this.splitContainer1.TabIndex = 0;
//
// groupBox1
//
this.groupBox1.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(459, 197);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "groupBox1";
//
// groupBox2
//
this.groupBox2.Dock = System.Windows.Forms.DockStyle.Fill;
this.groupBox2.Location = new System.Drawing.Point(0, 0);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(459, 197);
this.groupBox2.TabIndex = 0;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "groupBox2";
//
// Form2
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(465, 401);
this.Controls.Add(this.splitContainer1);
this.Name = "Form2";
this.Padding = new System.Windows.Forms.Padding(3);
this.Text = "Form2";
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.GroupBox groupBox2;

Why are programmatically added controls not shown?

Does anyone know why these controls are not shown on the form? If I add the controls with the same properties via design everything works just fine but if I use the same code from the designer in the form constructor with only other names nothing works.
private void CreatePlayingTab()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
//
// bunifuCustomLabel_Titel
//
BunifuCustomLabel bunifuCustomLabel_Titel = new BunifuCustomLabel();
bunifuCustomLabel_Titel.AutoSize = true;
bunifuCustomLabel_Titel.Font = new Font("Century Gothic", 11.25F, FontStyle.Bold, GraphicsUnit.Point, 0);
bunifuCustomLabel_Titel.ForeColor = Color.FromArgb(224, 224, 224);
bunifuCustomLabel_Titel.Location = new Point(19, 30);
bunifuCustomLabel_Titel.Name = "bunifuCustomLabel_Titel";
bunifuCustomLabel_Titel.Size = new Size(153, 18);
bunifuCustomLabel_Titel.Text = "#001 Wer ist Naruto?";
//
// bunifuCustomLabel_Interpret
//
BunifuCustomLabel bunifuCustomLabel_Interpret = new BunifuCustomLabel();
bunifuCustomLabel_Interpret.AutoSize = true;
bunifuCustomLabel_Interpret.Font = new Font("Century Gothic", 11.25F, FontStyle.Regular, GraphicsUnit.Point, 0);
bunifuCustomLabel_Interpret.ForeColor = Color.FromArgb(224, 224, 224);
bunifuCustomLabel_Interpret.Location = new Point(20, 52);
bunifuCustomLabel_Interpret.Name = "bunifuCustomLabel_Interpret";
bunifuCustomLabel_Interpret.Size = new Size(98, 20);
bunifuCustomLabel_Interpret.Text = "Studio Tokyo";
//
// windowsMediaPlayer
//
AxWindowsMediaPlayer windowsMediaPlayer = new AxWindowsMediaPlayer();
windowsMediaPlayer.Dock = DockStyle.Bottom;
windowsMediaPlayer.Enabled = true;
windowsMediaPlayer.Location = new Point(0, 117);
windowsMediaPlayer.Name = "windowsMediaPlayer";
windowsMediaPlayer.OcxState = ((AxHost.State)(resources.GetObject("mediaPlayer.OcxState")));
windowsMediaPlayer.Size = new Size(912, 513);
windowsMediaPlayer.uiMode = "None";
//
// panel_currentlyPlaying
//
Panel panel_currentlyPlaying = new Panel();
panel_currentlyPlaying.Controls.Add(windowsMediaPlayer);
panel_currentlyPlaying.Controls.Add(bunifuCustomLabel_Titel);
panel_currentlyPlaying.Controls.Add(bunifuCustomLabel_Interpret);
panel_currentlyPlaying.Dock = DockStyle.Fill;
panel_currentlyPlaying.Location = new Point(0, 100);
panel_currentlyPlaying.Name = "panel_Playing";
panel_currentlyPlaying.Size = new Size(912, 630);
panel_Media.Controls.Add(panel_currentlyPlaying);
}
I think you may have forgotten to add the controls to the form.
Use this.Controls.Add(Control Item);

How to hide an animated image on canvas?

I created an animated image to move on my canvas then I created another animated image ;
I want to hide just my first image after it's movement and before moving another;
I tried to set opacity of my drawing visual or image brush or etc zero;but all of my image
hide;
List<EllipseGeometry> eg = new List<EllipseGeometry>();
Path ballPath;
int c = 0;
foreach (Polyline p in pl)
{
if (p.Points.Count > 1)
{
ballPath = new Path();
FormattedText formattedText = new FormattedText(" " + (anl[c].DOffset).ToString() + "\n " + anl[c].playername + " ", CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("arial"),
20,
Brushes.Black);
formattedText.MaxTextWidth = 500;
formattedText.MaxTextHeight = 500;
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(il[c].Source, new Rect(4, 0, 26, 26));//30
drawingContext.DrawText(formattedText, new Point(1, 2));
drawingContext.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap((int)formattedText.WidthIncludingTrailingWhitespace, (int)formattedText.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
ImageBrush b = new ImageBrush(bmp);
b.Stretch = Stretch.Uniform;
ballPath.Fill = b;
mainwindow.animecan.Children.Add(ballPath);
////
int jy = 0;
for (int i = 0; i < anl.Count; i++)
{
try
{
if (anl[i].offset == m)
jy = anl[i].offset;
}
catch
{
}
}
if (multi && p.Uid == jy.ToString())//اگر آفست مالتی اسپید شده باشه
{
eg.Add(new EllipseGeometry(ms[ih].p1, 27, 27));
ballPath.Data = eg.First();// animatedEllipseGeometry;
PathFigure myPathFigure = new PathFigure();
PointCollection pe = new PointCollection();
pe.Add(ms[ih].p1);
pe.Add(ms[ih].p2);
myPathFigure.StartPoint = eg.First().Center;
myPathFigure.Segments.Add(
new PolyLineSegment(pe, true));
PathGeometry myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);
myPathGeometry = new PathGeometry();
myPathGeometry.Figures.Add(myPathFigure);//
PointAnimationUsingPath centerPointAnimation1 = new PointAnimationUsingPath();
centerPointAnimation1.PathGeometry = myPathGeometry;
centerPointAnimation1.Duration = TimeSpan.FromSeconds(ms[ih].sspeed);
centerPointAnimation1.BeginTime = TimeSpan.FromSeconds(ms[ih].delay);
centerPointAnimation1.FillBehavior = FillBehavior.HoldEnd;
eg.First().BeginAnimation(EllipseGeometry.CenterProperty, centerPointAnimation1);
eg.Remove(eg.First());
}
c++;
I believe that your problem is caused because your whole code block is executed 'at once' (before updating the UI), rather than 'line by line'. In order to make your call to the Visibility property update before execution reaches the end of the code block, you'll need to queue it on the Dispatcher object. Try this:
Dispatcher.CurrentDispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
{
yourControl.Visibility = Visibility.Collapsed;
});

Grid.children.clear thread error xmpp wpf

I am calling a method that has a Grid.Children.Clear() functionality. When calling it from different methods it works well. But when I call my the method from an xmpp_onmessage method. I am experiencing an error. “The calling thread cannot access this object because a different thread owns it.”
Here is the method that containts Grid.Children.Clear()the :
private void ConstructChatView(Boolean isChat)
{
System.Uri resourceUri = new System.Uri("Public/Images/chat_green-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo = Application.GetResourceStream(resourceUri);
System.Uri resourceUri2 = new System.Uri("Public/Images/chat_green-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo2 = Application.GetResourceStream(resourceUri2);
System.Uri resourceUri3 = new System.Uri("Public/Images/chat_blue-textarea.png", UriKind.Relative);
StreamResourceInfo streamInfo3 = Application.GetResourceStream(resourceUri3);
System.Uri resourceUri4 = new System.Uri("Public/Images/chat_blue-textarea-tail.png", UriKind.Relative);
StreamResourceInfo streamInfo4 = Application.GetResourceStream(resourceUri4);
BitmapFrame temp = BitmapFrame.Create(streamInfo.Stream);
var brush = new ImageBrush();
brush.ImageSource = temp;
BitmapFrame temp2 = BitmapFrame.Create(streamInfo2.Stream);
BitmapFrame temp3 = BitmapFrame.Create(streamInfo3.Stream);
var brush2 = new ImageBrush();
brush2.ImageSource = temp3;
BitmapFrame temp4 = BitmapFrame.Create(streamInfo4.Stream);
int ctr = 0;
chatGrid.Children.Clear();
if (isChat == true)
{
for (int i = 0; i < _messageView.Count; i++)
{
if ((!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
if (_messageView.ElementAt(i).IsMe == true)
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Right;
Message.Margin = new Thickness(0, 0, 5, 0);
Message.Background = brush2;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Bluetail = new Image();
Bluetail.Source = temp4;
Bluetail.HorizontalAlignment = HorizontalAlignment.Right;
Bluetail.Height = 10;
Bluetail.Width = 20;
Bluetail.Margin = new Thickness(0, -(0.7), 10, 0);
Grid.SetRow(Bluetail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Right;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Bluetail);
chatGrid.Children.Add(Sender);
}
else
{
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Margin = new Thickness(5, 0, 0, 0);
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(10, -(0.7), 5, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.HorizontalAlignment = HorizontalAlignment.Left;
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
}
else
{
for (int i = 0; i < _messageView.Count; i++)
{
if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
{
RowDefinition chatGridRow1 = new RowDefinition();
RowDefinition chatGridRow2 = new RowDefinition();
RowDefinition chatGridRow3 = new RowDefinition();
chatGrid.RowDefinitions.Add(chatGridRow1);
chatGrid.RowDefinitions.Add(chatGridRow2);
chatGrid.RowDefinitions.Add(chatGridRow3);
TextBlock Message = new TextBlock();
Message.Foreground = Brushes.White;
Message.Margin = new Thickness(0, 10, 300, 0);
Message.Padding = new Thickness(10, 10, 10, 10);
Message.HorizontalAlignment = HorizontalAlignment.Left;
Message.Background = brush;
Message.TextWrapping = TextWrapping.Wrap;
Message.Text = _messageView.ElementAt(i).Message;
Grid.SetRow(Message, ctr);
Grid.SetColumn(Message, 0);
ctr++;
Image Greentail = new Image();
Greentail.Source = temp2;
Greentail.HorizontalAlignment = HorizontalAlignment.Left;
Greentail.Height = 10;
Greentail.Width = 20;
Greentail.Margin = new Thickness(5, -(0.7), 0, 0);
Grid.SetRow(Greentail, ctr);
ctr++;
Label Sender = new Label();
Sender.Foreground = Brushes.White;
Sender.Margin = new Thickness(0, 0, 0, 10);
Sender.Content = "Sent By : " + _messageView.ElementAt(i).Name.ToString() + " " + _messageView.ElementAt(i).DateCreated.ToString();
Grid.SetRow(Sender, ctr);
Grid.SetColumn(Sender, 0);
ctr++;
chatGrid.Children.Add(Message);
chatGrid.Children.Add(Greentail);
chatGrid.Children.Add(Sender);
}
}
}
//for (int i = 0; i < _messageView.Count; i++)
//{
// if (_messageView.ElementAt(i).IsMe == true && (!_messageView.ElementAt(i).Message.ToString().Trim().Equals("")))
// {
// }
//}
ctr = 0;
scrollView.ScrollToEnd();
}
Any ideas? thanks
Most UI elements may only be modified in the UI thread. As your event handler is apparently invoked in a different thread, you have to use the Dispatcher to invoke your code in the UI thread.
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => chatGrid.Children.Clear()));
}
EDIT: You may also pass more code to the Invoke call by using an anonymous method:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() =>
{
// more code here
}));
}
Of course you may also put a bunch of code in another method and pass that to the Invoke call:
private void ConstructChatView(Boolean isChat)
{
Dispatcher.Invoke((Action)(() => ConstructChatViewInUI(isChat)));
}
private void ConstructChatViewInUI(Boolean isChat)
{
...
}

Adding columns and rows into a tablelayoutpanel row dynamically

Hi, I have a windows forms application written in c#. I use tablelayoutpanel that have 5 rows and a column. My question is how could we add red columns and row (they are shown in red color in the picture) into just row 3 in runtime/dynamically ? And how can we reach later to be able to add controls (labels, textboxes, buttons..) into them?
Thanks for advices..
Here an example :
private void GenerateControls()
{
TableLayoutPanel tableLayoutPanel1 = new TableLayoutPanel();
Button button1 = new Button();
Button button2 = new Button();
PictureBox pictureBox1 = new PictureBox();
TextBox textBox1 = new TextBox();
tableLayoutPanel1.SuspendLayout();
// tableLayoutPanel1
tableLayoutPanel1.ColumnCount = 2;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.Controls.Add(button2, 1, 0);
tableLayoutPanel1.Controls.Add(button1, 0, 0);
tableLayoutPanel1.Controls.Add(pictureBox1, 0, 1);
tableLayoutPanel1.Controls.Add(textBox1, 1, 1);
tableLayoutPanel1.Location = new System.Drawing.Point(12, 12);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 20));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 50F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 30F));
tableLayoutPanel1.Size = new System.Drawing.Size(388, 301);
tableLayoutPanel1.TabIndex = 0;
tableLayoutPanel1.CellPaint += new TableLayoutCellPaintEventHandler(tableLayoutPanel1_CellPaint);
// button1
button1.Dock = DockStyle.Fill;
button1.Location = new System.Drawing.Point(3, 3);
button1.Name = "button1";
button1.Size = new System.Drawing.Size(188, 144);
button1.TabIndex = 0;
button1.Text = "button1";
button1.UseVisualStyleBackColor = true;
// button2
button2.Dock = DockStyle.Fill;
button2.Location = new System.Drawing.Point(197, 3);
button2.Name = "button2";
button2.Size = new System.Drawing.Size(188, 144);
button2.TabIndex = 1;
button2.Text = "button2";
button2.UseVisualStyleBackColor = true;
// pictureBox1
pictureBox1.Dock = DockStyle.Fill;
pictureBox1.Location = new System.Drawing.Point(3, 153);
pictureBox1.Name = "pictureBox1";
pictureBox1.Size = new System.Drawing.Size(188, 145);
pictureBox1.TabIndex = 2;
pictureBox1.TabStop = false;
//pictureBox1.Image = Image.FromFile(#"C:\somepic.jpg");
// textBox1
textBox1.Dock = DockStyle.Fill;
textBox1.Location = new System.Drawing.Point(197, 153);
textBox1.Multiline = true;
textBox1.Name = "textBox1";
textBox1.Size = new System.Drawing.Size(188, 145);
textBox1.TabIndex = 3;
Controls.Add(tableLayoutPanel1);
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel1.PerformLayout();
}
This void will manipulate borders
void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
{
if (e.Column == 0)
{
var rectangle = e.CellBounds;
rectangle.Inflate(-1, -1);
ControlPaint.DrawBorder3D(e.Graphics, rectangle, Border3DStyle.Raised, Border3DSide.All); // 3D border
}
else if (e.Column == 1 && e.Row == 0)
{
var rectangle = e.CellBounds;
rectangle.Inflate(-1, -1);
ControlPaint.DrawBorder(e.Graphics, rectangle, Color.Red, ButtonBorderStyle.Dotted); // dotted border
}
}

Resources