I have listbox with Buttons. Every button have specific name -> button.Name = "button1".
I want to find specific button in listbox by Name.
I tried something like this:
if (listBox.Items.Contains(new Button().Name = "button2"))
{
MessageBox.Show("TEST");
}
But it doesnt work.
How to find it?
You need to check: 1. If the item is a Button 2. If its name is the same (use == not = as in your code)
foreach(var i in listBox.Items)
{
if (i is Button && (i as Button).Name=="button2")
{
MessageBox.Show("TEST");
}
}
If you have your ItemsControl item with you then you can iterate its Visualtree to reach to your button using VisualTreeHelper
Recursive find child is explained in this post How can I find WPF controls by name or type?
Related
My problem is that i've got a panel called PanelNewFriend, where i'm dynamically creating buttons from all users from a mysql database. So when someone clicks on a user and sends an invite , what should be happening is that it should remove all buttons (Except for the back button which has a tag of "1") and then place all the buttons again for the new list of all users.
When creating the buttons i assigned a tag with value "0" to them. All buttons have it even though i don't think the problem lies in the tag.
I'm using this code to remove all buttons in the panel.
foreach (Button item in PanelNewFriend.Controls.OfType<Button>())
{
if (item.Tag == "0")
{
PanelNewFriend.Controls.Remove(item);
}
}
I've tried multiple things, ranging from foreach Control item and oftype Control. To changing the item.Tag != "1" and item.Tag == "". None of this worked
But when i actually execute the code and add breaking points I can see that there are 4 buttons in the panel. But when i go through each foreach cycle, it only selects 2 of the 4 buttons. So since it only selects 2 buttons it is only deleting 2 and leaving the other 2 alone.
Any idea what could be causing this and how to fix it?
Classic collection modification problem here. You're modifying the collection as you're iterating over it. That will result in unexpected behavior. Ideally you should be getting InvalidOperationException but sadly ControlCollection doesn't implement this check.
You have two options. Either take a copy of the collection and iterate over the copy or use a reverse for loop.
var buttonsToRemove = PanelNewFriend.Controls
.OfType<Button>()
.Where(x=> x.Tag == "0")
.ToArray();//Take a copy
foreach (Button item in buttonsToRemove)
{
PanelNewFriend.Controls.Remove(item);
}
Try like this
List<Button> removeList = new List<Button>();
foreach (Button item in PanelNewFriend.Controls.OfType<Button>())
{
if (item.Tag == "0")
{
removeList.Add(item);
}
}
foreach (Button item in removeList)
PanelNewFriend.Controls.Remove(item);
I'm trying to load a form with different information depending on which component of my listbox I double click. If I get which box was clicked(box 1, box2, etc.), that would be enough.
I've tried using the Doubleclick event, but it returns an object, and I'm not quite sure what to do with this object to get what I need.
Heres my code right now:
for (int i = 0; i <= (Program.Customers.Count) - 1; i++)
{
if (Program.Customers[i].Name == searchTerm)
{
SearchIndex.Add(i);
listBox1.Items.Add(((Program.Customers[i].ID + " - " + Program.Customers[i].Name)));
}
}
listBox1.Show();
What would be the best way to get which box was clicked? I need the ID, but I can get that with box was clicked.
Thanks!
In the simplest case, you can directly compare the sender argument with your ListBox control instances, for example:
if (sender == listBox1)
{
// ...
}
To get more information out of sender you need to cast it to something more specific first. So if you know your double click handler was only attached to list boxes, you can do
var listbox = (ListBox)sender;
and then access any of the properties of ListBox (such as Tag, which I mention because it's there specifically for your custom needs).
I made a custom FindControl function to find a control within all childs of one control I pass in parameter.
But I don't manage to have a hand over the button used to create a user ,in a CreateUserWizard Control.
I kept the default style, do anyone knows the name (ID) of this button?
I saw buttons like "ContinueButtonButton", "FinishButton", but they don't seem to be the one I am searching for, because I then have this line:
this.Form.DefaultButton = Tools.FindControl(CreateUserWizard1, "FinishButton").UniqueID;
And the create user event is not fired when I hit enter.
Any idea?
I finally found it, its ID is "StepNextButtonButton"
how about try something like
foreach (Control ctrl in this.form1.Controls)
{
if (ctrl.GetType() == typeof(Button) && (ctrl as Button).Text == "Button2")
{
this.form1.DefaultButton = ctrl.ID;
}
}
How can I tell my TabControl to set the focus to its first TabItem, something like this:
PSEUDO-CODE:
((TabItem)(MainTabControl.Children[0])).SetFocus();
How about this?
MainTabControl.SelectedIndex = 0;
this.tabControl1.SelectedTab = this.tabControl1.TabPages["tSummary"];
I've found it's usually a best practice to name your tabs and access it via the name so that if/when other people (or you) add to or subtact tabs as part of updating, you don't have to go through your code and find and fix all those "hard coded" indexes. hope this helps.
I realise this was answered a long time ago, however a better solution would be to bind your items to a collection in your model and expose a property that selected item is bound to.
XAML:
<!-- MyTemplateForItem represents your template -->
<TabControl ItemsSource="{Binding MyCollectionOfItems}"
SelectedItem="{Binding SelectedItem}"
ContentTemplate="{StaticResource MyTemplateForItem}">
</TabControl>
Code Behind:
public ObservableCollection<MyItem> MyCollectionOfItems {
get;
private set;
}
private MyItem selectedItem;
public MyItem SelectedItem{
get { return selectedItem; }
set {
if (!Object.Equals(selectedItem, value)) {
selectedItem = value;
// Ensure you implement System.ComponentModel.INotifyPropertyChanged
OnNotifyPropertyChanged("SelectedItem");
}
}
}
Now, all you have to do to set the item is:
MyItem = someItemToSelect;
You can use the same logic with the SelectedIndex property, further, you can use the two at the same time.
This approach allows you to separate your model correctly from the UI, which could allow you to replace the TabControl with something else down the line but not requiring you to change your underlying model.
Look at the properties for the tab control...
Expand the TabPages properties "collection"...
Make note of the names you gave the members.
ie. a tab control called tabMain with 2 tabs called tabHeader and tabDetail
Then to select either tab...You have to set it with the tabname
tabMain.SelectedTab = tabHeader;
tabControl1.SelectedTab = item;
item.Focus();
Basically all of the answers here deal with SELECTION, which does not answer the question.
Maybe that is what OP wanted, but the question very specifically asks for FOCUS.
TabItem item = (TabItem)MainTabControl.Items[0];
// OR
TabItem item = (TabItem)MainTabControl.SelectedItem;
// Then
item.Focus();
tabControl.SelectedItem = tabControl.Items[0];
If you have a Tabcontroller named tabControl you could set the selectedIndex from different methods, i use following methods mostly.
codebehind:
tabControl.SelectedIndex = 0; // Sets the focus to first tabpanel
clientside:
First, put the following javascript in your aspx/ascx file:
<script type="text/javascript">
function SetActiveTab(tabControl, activeTabIndex) {
var activeTab = tabControl.GetTab(activeTabIndex);
if(activeTab != null)
tabControl.SetActiveTab(activeTab);
}</script>
Then add following clientside event to prefered controller:
OnClientClick="function(s, e) { SetActiveTab(tabControl, 0);
it's better to use the following type of code to select the particular
item in the particular tab...
.
private void PutFocusOnControl(Control element)
{
if (element != null)
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,
(System.Threading.ThreadStart)delegate
{
element.Focus();
});
}
And in calling time... tabcontrol.isselected=true;
PutFocusOnControl(textbox1);
will works fine...
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
'MsgBox(TabControl1.SelectedIndex)
If TabControl1.SelectedIndex = 0 Then
txt_apclntFrstName.Select()
Else
txtApplcnNo.Select()
End If
End Sub
It worked for me to set focus to the last tab just after I open it:
//this is my assignment of the collection to the tab control
DictTabControl.DataContext = appTabs.DictTabs;
//set the selected item to the last in the collection, i.e., the one I just added to the end.
DictTabControl.SelectedItem = DictTabControl.Items[(DictTabControl.Items.Count-1)];
Is there a straighforward way to set additional text to appear in a tooltip when a user's mouse is held over an item in a CheckedListBox?
What I would expect to be able to do in code is:
uiChkLstTables.DisplayOnHoverMember = "DisplayOnHoverProperty"; //Property contains extended details
Can anyone point me in the right direction to do this? I've already found a couple of articles that involve detecting which item the mouse is currently over and creating a new tooltip instance, but this sounds a little too contrived to be the best way.
Thanks in advance.
Add a Tooltip object to your form and then add an event handler for the CheckedListBox.MouseHover that calls a method ShowToolTip();
Add MouseMove event of your CheckedListBox which has the following code:
//Make ttIndex a global integer variable to store index of item currently showing tooltip.
//Check if current location is different from item having tooltip, if so call method
if (ttIndex != checkedListBox1.IndexFromPoint(e.Location))
ShowToolTip();
Then create the ShowToolTip method:
private void ShowToolTip()
{
ttIndex = checkedListBox1.IndexFromPoint(checkedListBox1.PointToClient(MousePosition));
if (ttIndex > -1)
{
Point p = PointToClient(MousePosition);
toolTip1.ToolTipTitle = "Tooltip Title";
toolTip1.SetToolTip(checkedListBox1, checkedListBox1.Items[ttIndex].ToString());
}
}
Alternately, you could use a ListView with checkboxes instead. This control has
builtin support for tooltips.
Contrived or not; that's what there is...
I'm not aware of an easier way than you have already described (although I'd probably re-use a tooltip instance, rather than creating new all the time). If you have articles that show this, then use them - or use a 3rd party control that supports this natively (none leap to mind).
I would like to expand upon Fermin's answer in order to perhaps make his wonderful solution slightly more clear.
In the form that you're working in (likely in the .Designer.cs file), you need to add a MouseMove event handler to your CheckedListBox (Fermin originally suggested a MouseHover event handler, but this did not work for me).
this.checkedListBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.showCheckBoxToolTip);
Next, add two class attributes to your form, a ToolTip object and an integer to keep track of the last checkbox whose tool tip was shown
private ToolTip toolTip1;
private int toolTipIndex;
Finally, you need to implement the showCheckBoxToolTip() method. This method is very similar to Fermin's answer, except that I combined the event callback method with the ShowToolTip() method. Also, notice that one of the method parameters is a MouseEventArgs. This is because the MouseMove attribute requires a MouseEventHandler, which then supplies MouseEventArgs.
private void showCheckBoxToolTip(object sender, MouseEventArgs e)
{
if (toolTipIndex != this.checkedListBox.IndexFromPoint(e.Location))
{
toolTipIndex = checkedListBox.IndexFromPoint(checkedListBox.PointToClient(MousePosition));
if (toolTipIndex > -1)
{
toolTip1.SetToolTip(checkedListBox, checkedListBox.Items[toolTipIndex].ToString());
}
}
}
Run through your ListItems in your checkbox list of items and set the appropriate text as the item 'title' attribute, and it will display on hover...
foreach (ListItem item in checkBoxList.Items)
{
//Find your item here...maybe a switch statement or
//a bunch of if()'s
if(item.Value.ToString() == "item 1")
{
item.Attributes["title"] = "This tooltip will display when I hover over item 1 now, thats it!!!";
}
if(item.Value.ToString() == "item 2")
{
item.Attributes["title"] = "This tooltip will display when I hover over item 2 now, thats it!!!";
}
}