I have a question - I was coding happily a quick little feature to an app, which was a simple comparison output window.
Basically, user clicks a button and I generate a window with a datagrid of two columns of data.
It's all great and a five minutes code living inside one method with no unnecessary reference to anything else. The only problem I encountered was when I wanted to add a TopMost checkbox to this window.
How do I bind the IsChecked property of the box to the TopMost property of the window?
var checkbox = new CheckBox();
checkbox.Name = "cb";
checkbox.Content = "Top most";
var grid = new DataGrid();
grid.ItemsSource = wcList;
grid.Margin = new Thickness(5);
var panel = new StackPanel();
panel.Children.Add(checkbox);
panel.Children.Add(grid);
var win = new Window();
//Binding b = new Binding("cb");
//b.Mode = BindingMode.TwoWay;
//b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
//win.SetBinding(Window.TopmostProperty, b);
win.Title = "WordCount comparison";
win.Content = panel;
win.SizeToContent = SizeToContent.WidthAndHeight;
win.Icon = this.Icon;
win.Show();
This was supposed to be a 5-minutes one-off method, which is why I don't want to go as far as adding any xaml or properties into the code.
Cheers
Bartek
The other way around as you tried (in the commented code):
checkbox.SetBinding(CheckBox.IsCheckedProperty, new Binding("Topmost") { Source = win });
just after you instantiated your win variable.
I am new at C# & XAML development. I created a metro app with several textboxes. These textboxes are loaded in XAML data through a StackPanel in C# code, it has to be hardcoded. The problem is, I have no clue how I can add some empty spaces between every single textbox. Has anyone an idea?
The Code :
private void AddLastestCreatedField()
{
// Load the last created Field From DB
DBFunction.FieldTypes latestField;
DBFunction.Class1 myDBClass = new DBFunction.Class1();
latestField = myDBClass.GetLastestField();
// add new textbox and put it on the screen
var dragTranslation = new TranslateTransform();
//Generate the TextBox
TextBox fieldTextBox = new TextBox();
fieldTextBox.Name = "fieldTextBox_" + latestField.ID.ToString();
fieldTextBox.FontSize = 15;
fieldTextBox.Background.Opacity = 0.8;
ToolTip toolTip = new ToolTip();
toolTip.Content = latestField.Description;
ToolTipService.SetToolTip(fieldTextBox, toolTip);
fieldTextBox.IsReadOnly = true;
// Add Drag and Drop Handler for TextBox
fieldTextBox.ManipulationMode = ManipulationModes.All;
fieldTextBox.ManipulationDelta += fieldTextBox_ManipulationDelta;
fieldTextBox.ManipulationCompleted += fieldTextBox_ManipulationCompleted;
fieldTextBox.RenderTransform = dragTranslation;
dragTranslationDict.Add(fieldTextBox.Name, dragTranslation);
fieldTextBox.RenderTransform = dragTranslation;
// Add TextBox to a List to control later
TxtBoxList.Add(fieldTextBox);
// Generate TextBlock for each TextBlock
TextBlock fieldTextBlock = new TextBlock();
// fieldTextBlock.Name = "fieldTextBlock_" + cnt.ToString();
fieldTextBlock.TextAlignment = TextAlignment.Right;
fieldTextBlock.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
fieldTextBlock.Name = "fieldTextBlock_" + latestField.ID.ToString();
fieldTextBlock.Text = latestField.Name;
fieldTextBlock.FontSize = 15;
fieldTextBlock.Height = 33;
// Add Drag and Drop Handler for TextBlock
var dragTranslation2 = new TranslateTransform();
fieldTextBlock.RenderTransform = dragTranslation2;
dragTranslationDict2.Add(fieldTextBlock.Name, dragTranslation2);
// Add TextBlock to a list to control later
TxtBlockList.Add(fieldTextBlock);
TextBoxStack.Children.Add(fieldTextBox);
TextBlockStack.Children.Add(fieldTextBlock);
}
I'll skip the usual "What have you tried?" question and say you probably can get what you need by setting the Margin property on the TextBox - the Margin property will add "space" around the control size as a sort of padding (not to be confused with the Padding property, which will add space inside the control extents)
I don't know what you are really up to, but either use the Margin-property of the textbox. It defines, how much space there will be around the control,
See MSDN for more information.
I'm having an issue with a Windows Forms project. I change tabs but the change does not reflect unless I maximize,minimize,or restore the entire window. After that the newly selected tab will show it's child contents.
I've narrowed the issue down to my trying to programmatic create and name a datagridview
I can do this:
logs_datagrid.Name = "datagrid_logs";
logs_datagrid.AutoSize = true;
logs_datagrid.Dock = DockStyle.Fill;
logs_datagrid.Font = new Font("Microsoft Sans Serif", 8.25F);
logs_datagrid.DataSource = dt_logs_google;
logs_datagrid.AllowUserToAddRows = false;
logs_datagrid.BackColor = System.Drawing.Color.White;
logs_datagrid.BringToFront();
splitContainer2.Panel2.Controls.Add(logs_datagrid);
but as soon as I try to programatically apply edits to the datagridview columns the issue occurs. Just uncommenting the top line here will cause the error.
DataGridViewColumn dvg_col_1 = logs_datagrid.Columns[0];
// DataGridViewColumn dgv_col_2 = logs_datagrid.Columns[1];
// DataGridViewColumn dgv_col_3 = logs_datagrid.Columns[3];
//dgv_col_1.ReadOnly = true;
// dgv_col_1.MinimumWidth = 200;
//dgv_col_2.ReadOnly = true;
//dgv_col_2.MinimumWidth = 200;
//dgv_col_3.ReadOnly = true;
//dgv_col_3.MinimumWidth = 200;
// dgv_col_3.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
[edit] Thank you for the help!
Perhaps Update();.
(Didn't check this case, but I've seen Update(); work, when Invalidate(); didn't.)
Try this.Invalidate() of your control
http://windowsclient.net/articles/windowsformspainting.aspx
I have a ComboBox that is bound to a DataSource. I want to dynamically add items to the ComboBox based on certain conditions. So what I've done is add the options to a new list, and then change the DataSource of the ComboBox like so:
cbo.DataSource = null;
cbo.DataSource = cbos;
cbo.DisplayMember = "Title";
cbo.ValueMember = "Value";
Then, I check cbo.Items.Count, and it has not incremented - it does not equal the count of the DataSource. Any ideas what I can do here?
Note this is WinForms and not ASP.NET.
Did you check the Count immediately or at a later time? There is the possibility that the ComboBox does not actually update it's contents until there is an operation such as a UI refresh and hence the count will be off until that time.
On case where this may happen is if you update the DataSource before the Handle is created for the ComboBox. I dug through the code a bit on reflector and it appears the items will not be updated in this case until the ComboBox is actually created and rendered.
If anyone experiences this problem on a dynamically added combobox, the answer is to ensure that you add the combobox to the controls of a container in the form.
By adding "this.Controls.Add(cbo);" to the code before setting the datasource, the problem goes away.
I've found the cause...
I took out the cbo.Datasource = null line.. and added a cbo.Invalidate() at the end. This has solved the problem.
Thanks all for the advice.
cbo.DataSource = null;
cbo.DataSource = cbos;
cbo.DisplayMember = "Title";
cbo.ValueMember = "Value";
Now before setting cbo.SelectedValue, or relying on Items to be up-to-date, call
cbo.CreateControl ;
and Items will be re-calculated.
The problem is that SelectedValue/SelectedIndex, which are WinForms properties, only accept the values that are legal according to the Items list, but that one is built only after GUI interaction, i.e. after instantiating a "real" Windows GUI combo box, i.e. after obtaining a Windows handle for the combobox.
CreateControl forces the creation of the Windows handle, no matter what.
ComboBox cbNew = new ComboBox();
cbNew.Name = "cbLine" + (i+1);
cbNew.Size = cbLine1.Size;
cbNew.Location = new Point(cbLine1.Location.X, cbLine1.Location.Y + 26*i);
cbNew.Enabled = false;
cbNew.DropDownStyle = ComboBoxStyle.DropDownList;
cbNew.DataSource = DBLayer.GetTeams(lineName).Tables[0];
cbNew.DisplayMember = "teamdesc";
cbNew.ValueMember = "id";
Console.WriteLine("ComboBox {0}, itemcount={1}", cbNew.Name, cbNew.Items.Count);
// The output displays itemcount = 0 for run-time created controls
// and >0 for controls created at design-time
gbLines.Controls.Add(cbNew);
TO
ComboBox cbNew = new ComboBox();
cbNew.Name = "cbLine" + (i+1);
cbNew.Size = cbLine1.Size;
cbNew.Location = new Point(cbLine1.Location.X, cbLine1.Location.Y + 26*i);
cbNew.Enabled = false;
cbNew.DropDownStyle = ComboBoxStyle.DropDownList;
Console.WriteLine("ComboBox {0}, itemcount={1}", cbNew.Name, cbNew.Items.Count);
// The output displays itemcount = 0 for run-time created controls
// and >0 for controls created at design-time
gbLines.Controls.Add(cbNew);
cbNew.DataSource = DBLayer.GetTeams(lineName).Tables[0];
cbNew.DisplayMember = "teamdesc";
cbNew.ValueMember = "id";
The DataSource, DisplayMember and ValueMember property must be set after the control has been added to its container.
By adding "this.Controls.Add(cbo);" to the code before setting the datasource, the problem goes away.
//Create dynamic combobox and add to Panel
ComboBox ddCombo = new ComboBox();
controls = new Control[1] { ddCombo };
panel.Controls.AddRange(controls);
//After creating add to table layout
tableLayoutPanel.Controls.Add(panel, 0, 0);
ddCombo .Name = "ddName";
ddCombo .Width = 200;
ddCombo .Location = new Point(x, y); ddCombo .DataSource = ds;//or any List
ddCombo .SelectedIndex = ddCombo .Items.Count - 1;
Just to clarify are you calling the count() method
After calling the databind() method
This code produces 2 in the message box for me, can you try it and see how it behaves for you?
You can paste it into a console application, and add a reference to System.Windows.Forms and System.Drawing.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
namespace SO887803
{
static class Program
{
[STAThread]
static void Main()
{
Application.Run(new MainForm());
}
}
public partial class MainForm : Form
{
private Button _Button;
private ComboBox _ComboBox;
public MainForm()
{
_Button = new Button();
_Button.Text = "Test";
_Button.Location = new Point(8, 8);
_Button.Click += _Button_Click;
Controls.Add(_Button);
_ComboBox = new ComboBox();
_ComboBox.Location = new Point(8, 40);
Controls.Add(_ComboBox);
}
private void _Button_Click(object sender, EventArgs e)
{
List<Item> items = new List<Item>();
items.Add(new Item("A", "a"));
items.Add(new Item("B", "b"));
_ComboBox.DataSource = null;
_ComboBox.DataSource = items;
_ComboBox.DisplayMember = "Title";
_ComboBox.ValueMember = "Value";
MessageBox.Show("count: " + _ComboBox.Items.Count);
}
public class Item
{
public String Title { get; set; }
public String Value { get; set; }
public Item(String title, String value)
{
Title = title;
Value = value;
}
}
}
}
comboBox1.DataSource=somelist;
int c1=comboBox1.DataSource.Count; // still zero
BindingContext dummy = this.comboBox1.BindingContext;// Force update NOW!
int c2=comboBox1.DataSource.Count; // now it equals somelist.Count
I had the same problem (Im working with VS 2005).
What you need to do is set the DataSource to null, clear the items, reassign the datasource , display and value members.
Eg
cbo.DataSource = null;
cbo.Items.Clear();
cbo.DataSource = cbos;
cbo.DisplayMember = "Title";
cbo.ValueMember = "Value";
Old thread, but I tried some of these solutions, along with suspending/resuming the bindingcontext, binding to and resetting a binding source, and just plain reloading the form. None worked to update my control with the newly bound data at the time of my .datasource setting (my items.count was empty, just like the OP).
Then I realized that my combobox was on a tabpage that was getting removed at the start of the code, and later re-added (after my databinding). The binding event did not occur until the tabpage was re-added.
Seems obvious in retrospect, but it was very difficult to detect at runtime, due to the order of calls and inability to see when things were changing.
Try this code.
cbo.BindingContext = new BindingContext();
cbo.DataSource = null;
cbo.DataSource = cbos;
cbo.DisplayMember = "Title";
cbo.ValueMember = "Value";
Maybe your ComboBox`s BindingContext is null.
Ba salam,
you can simply refresh the UI by preformLayout() function;
Example:
comboBox1.performLayout();
regards
mohsen s
please try this:
cbo.Parent = <your panel control>;
cbo.DataSource = null;
cbo.DataSource = cbos; cbo.DisplayMember = "Title";
cbo.ValueMember = "Value";
MessageBox.Show(string.Format("itemcount is {0}", cbo.Items.Count);
I think your question sames like I met today.
I have a program that I want each person to have their own tab, each tab would be identical, however I would like to remove a tab if I need to.
private void addPerson(string name)
{
TabPage tmp = new TabPage();
ListView tmpList = new ListView();
Button tmpButton = new Button();
this.SuspendLayout();
this.tabFrame.SuspendLayout();
tmp.SuspendLayout();
tmpList.SuspendLayout();
tmpButton.SuspendLayout();
...
//build the controll itself
tmp.Controls.Add(tmpButton);
tmp.Controls.Add(tmpList);
tmp.Location = new System.Drawing.Point(4, 22);
tmp.Name = name.Replace(' ', '_');
tmp.Padding = new System.Windows.Forms.Padding(3);
tmp.Size = new System.Drawing.Size(284, 240);
tmp.TabIndex = 3;
tmp.Text = name;
tmp.UseVisualStyleBackColor = true;
//add it to frame
this.tabFrame.Controls.Add(tmp);
tmpButton.ResumeLayout(true);
tmpList.ResumeLayout(true);
tmp.ResumeLayout(true);
this.tabFrame.ResumeLayout(true);
this.ResumeLayout(true);
{
Name will be in the form "Scott Chamberlain" so I remove the spaces and use underscores for the name field. I can add tabs fine, they show up correctly formated, however when I try to remove the tab using the code:
private void removePerson(string name)
{
this.SuspendLayout();
this.tabFrame.SuspendLayout();
this.tabFrame.Controls.RemoveByKey(name.Replace(' ', '_'));
this.tabFrame.ResumeLayout(true);
this.ResumeLayout(true);
}
The tab does not disappear from my program. What am I missing to remove a tab?
(source: codinghorror.com)
Creating a simple TabPage with a specific Name and adding it to Controls or TabPages works and so does removing it with RemoveByKey on both Controls and TabPages.
Is there any code that might later change the name?
Use tabFrame.TabPages instead of tabFrame.Controls, for both the Add() and RemoveByKey() operations.
TabPages is a more specified version of Controls, and if such a situation occurs you are better of with the more specialized option.