Accessing other buttons from one button's "click" method - c#

How can I access other buttons from click method of one button? I'm working in Milestone SDK (c#, visual studio).
I've tried to use "this.", but it obviously doesn't work... (I'm novice in c#)...
In example below I can change "CONTENT" for bbt button object (bbt.Content = "TEST";):
private void bbt_Click(object sender, RoutedEventArgs e)
{
var bbt = sender as Button;
bbt.Content = "TEST";
}
but how can I change content for other buttons, defined in my code? For example, another button name is "action1"?
Maybe there is a way to declare something like that:
var bbt = sender as Button;
but for all other buttons so I can access them like I'm accessing "bbt"?
Would like to have a code that will allow mi to do:
action1.Content = "TEST";
where action1 is another button.
It looks like I need to add some prefix before referring to "action1", because otherwise it's not visible and generates:
CS0103 The name 'action1' does not exist in the current context

Looks like you are trying to change the button label.
If the button already exist just use:
private void bbt_Click(object sender, RoutedEventArgs e)
{
bbt.Text= "TEST";
}

If you have a container like a flowLayoutPanel,panels where the child is buttons you can use the forloop to get all the buttons and change it contents
//if without a container you must Name your buttons to button1,button2,button3
int i=0;
while(true){
i++;
Button button = new Button();
button.Name = "button"+i.toString();//output button1 to n
WindowsFormName.Controls.Add(button);
}
private void bbt_Click(object sender, RoutedEventArgs e)
{
//loop all controls
int y=0;
foreach(Control control in WindowsFormName.Controls){
y++;
string name = "Button"+y.toString();
//check if names are button1 or buttonN
if(control.Name.Equals(name){
control.Content = "TEST";
}
}
}

If the button was at the same hierarchy as the button being clicked you should be able to access it normally (e.g. action1.Text = "hello world";). I believe your problem may be that the button is on a child control.
If that is the case you have to write some type of recursive code to find the desired button (see the answer to this post to search for a control recursively Get control by name, including children)
Then call it:
var actionButton = this.FindControlRecursively<Button> ("action1");

Related

Change Value of a Dynamically Created Text Box when button is clicked C#

I have dynamically created a button using a function I made which is meant to increase the value of another button created using a similar function. I'm able to retrieve the name of the dynamically created textbox, but since it is dynamically created, I can't reference it.
I've tried to pass the textbox through as a parameter, but it doesn't appear that I'm able to pass extra parameters:
Button ButtonDecreaseValue= addButton(ItemName, "-");
TextBox TextBoxItemAmount = addTextBox(ItemName, "0");
So, how would I change the value of textbox one when ButtonRemoveItem is clicked?
I've created an event handler for the button, like so:
ButtonIncreaseValue.Click += new EventHandler(ItemDecreased);
But, inside the event handler, I'm unsure how I would change the textbox name.
private void ItemDecreased(object sender, EventArgs e)
{
Button currentItem = (Button)sender;
int ItemNo = Convert.ToInt32(currentItem.Tag);
DataRow ItemInfo = getItemDetails(ItemNo);
ItemInfo[0].ToString();
}
When clicking the button, the corresponding textbox should decrease in value.
Assuming this is Windows Forms
You said you have the name of the TextBox? You should be able to find it with that.
private void ItemDecreased(object sender, EventArgs e)
{
string textBoxName = HoweverYouGetTheDynamicTextBoxName();
// Assumptions:
// 1. ItemDecreased is a method on a Form or a UserControl.
// 2. There is only one TextBox with the given name in the Form or UserControl.
// 3. The TextBox is added to the Form or UserControl's Controls property.
TextBox tb = Controls.Find(textBoxName, true).OfType<TextBox>().SingleOrDefault();
if (tb is null)
{
// Couldn't find the text box for some reason.
}
// tb references the dynamically created text box.
}

TextBox AutoCompleteStringCollection Suggest

I have created a form in C# with a CustomSource for a textbox:
public partial class FormLookup : Form
{
AutoCompleteStringCollection source = new AutoCompleteStringCollection();
public FormLookup()
{
InitializeComponent();
source.Add("Test");
source.Add("TestItem");
source.Add("TestValue");
this.textBox1.AutoCompleteCustomSource = source;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
}
The result looks like this:
The purpose of what I am looking for is to select multiple values from the auto suggestion list. When the user selected the first value, a seperator like ';' should trigger the auto suggestion again.
It should look like this:
Maybe some code/idea in the _TextChanged method?
Is it possible in C# to highlight the selected value like in pic2?
Your ideas are welcome!
You need to create your custom control for this requirement.
I have created similar one. posting logic and code - hope it may help you in getting basic Idea.
You need to create two user controls.
Custom Control (container for second user control + text box which you show us in question)
Tag control (will contain label to show Text of tag and link label 'x' to remove it)
Together it will create a visualization of single unit custom control. where you can type (with you drop down suggestion) and once you press ',' , it will create a tag and store it within.
It will look like below,
Here is code for that.
Custom Control will have following cnntrols by default
private System.Windows.Forms.FlowLayoutPanel flayoutCustomControlContainer;
public System.Windows.Forms.TextBox textBox1; //Marking this public so it can be directly accessed by external code.
here flayoutCustomControlContainer is containing textBox1 by default.
textBox1 will have Key Up event, which will be like below.
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Oemcomma) //we will perform this on every ',' press
{
flayoutCustomControlContainer.Controls.Remove(textBox1);
TagControl tag = new TagControl(); //creating new Tag control
tag.lblTagName.Text = textBox1.Text.TrimEnd(",".ToCharArray());
tag.Remvoed += tag_Remvoed; //subscribing "Removed" event of Tag
tag.Width = tag.lblTagName.Width + 50;
tag.Height = tag.lblTagName.Height + 5;
flayoutCustomControlContainer.Controls.Add(tag);
textBox1.Text = "";
flayoutCustomControlContainer.Controls.Add(textBox1);
textBox1.Focus();
}
}
void tag_Remvoed(object sender, EventArgs e)
{
this.flayoutCustomControlContainer.Controls.Remove((Control)sender);
textBox1.Focus();
}
Constructor of Custom Control, as you shown in question,
public CustomControl()
{
InitializeComponent();
source.Add("Test");
source.Add("TestItem");
source.Add("TestValue");
this.textBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
this.textBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
this.textBox1.AutoCompleteCustomSource = source;
}
Now, Tag Control.
private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1;
public System.Windows.Forms.Label lblTagName;
private System.Windows.Forms.LinkLabel llblRemove;
link label, llblRemove will have link lable click event which will raise an event, which Custom control is listing.
private void llblRemove_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
if (Remvoed != null)
Remvoed(this, EventArgs.Empty);
}
Now, use this Custom Control anywhere you want to use.
I have uploaded working example project on GitHub.
Find a Link
You need create your own component.
The structure can be be:
Panel (the main container with white background and border)
|-> FlowLayoutPanel (the container for already added tags); Dock = Left
| |-> TagControl (you custom control for tag label)
| |-> ... (more tags if required)
|-> TextBox (the one with autocompletion with no borders); Dock = Fill;
You can encapsulate to your own Control/UserControl and use that event from Toolbox in designer.

Dynamically creating HTML button control and nesting i tag within it

I created a simple HTML Button within c# as
Button btn = new Button();
btn.ID="myID";
btn.Click+=new EventHandler(someFunc);
which works perfectly fine as expected. But all I need to do is to insert an icon within it.
Similar to something like this.
<button class="mdl-button mdl-js-button mdl-button--fab mdl-button--colored">
<i class="material-icons">add</i>
</button>
Could someone please guide as to how to insert this within the button?
Instead of using Button you have to use HtmlButton and have server click event, because WebControls Button will render like <input type so it cannot have another control inside it.
Also someFunc should be event not string
Following is the complete code that you can use
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
System.Web.UI.HtmlControls.HtmlButton btn = new System.Web.UI.HtmlControls.HtmlButton();
btn.ID = "myID";
btn.Attributes["class"] = "mdl-button mdl-js-button mdl-button--fab mdl-button--colored";
btn.ServerClick += new EventHandler(someFunc);
btn.InnerHtml = "<i class=\"material-icons\">add</i>";
// you can add your button to some other parent control or to form
myCustomPanel.Controls.Add(btn);
}
}
protected void someFunc(object sender, EventArgs e)
{
// your code
}
Make sure to add your button in form or some other control inside form.
You can create a HtmlGenericControl object and add all the relevant properties like InnerText,class etc and finally add this object to the button's controls collection. This will give you the expected output:-
HtmlGenericControl iTag = new HtmlGenericControl("i");
iTag.InnerText = "Add";
iTag.Attributes["class"] = "material-icons";
btn.Controls.Add(iTag);

c# xaml selecting controls using Name

I have the following dispatch routine in VS2013 C#:
private void B_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string src = btn.Name.ToString();
string foo = "G" + src.Substring(1);
G0.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
It currently changes the visibility of G0. I want to change the code so that if Button B123 is pressed, then G123.Visibility is changed.
Thanks,
Dan
Note: This is a generic eventhandler for the buttons. There are 100's of buttons so an individual handler for each button is not practical. It could also be the handler from a dropdown or text box. G123 is a random control on the XAML page. The point is, given a string that contains the Name, how do I find the associated control so that I can modify its properties?
I'm not sure that I correctly understand your question, so I may be guessing that if button buttons B123 and G123 are related to each other by the number 123. In general, I suppose you want to change the visibility of button GX if button BX is changed.
In order to find all controls in the Window, have a look at the solution provided by Bryce Kahle, see Find all controls in WPF Window by type. In your buttenclick handle, do something like
private void B_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string src = btn.Name.ToString();
string identifier= src.Substring(1);
foreach (var btn in FindVisualChildren<Button>(this).Where(b => b.Name.EndsWith(identifier)))
{
if(btn.Name.StartsWith("G"))
btn.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
Hope that helps.
In the comments, user Clemens gave the answer. (Since he didn't give it as an answer, I can't vote it up.)
Using FindName, I was able to get to the properties of the desired control:
private void B_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button)sender;
string src = btn.Name.ToString();
string foo = "G" + src.Substring(1);
Windows.UI.Xaml.Shapes.Rectangle rect = (Windows.UI.Xaml.Shapes.Rectangle)this.FindName(foo);
rect.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
This has the flexibility so that I can change the fill, contents, text, foreground, style, etc. for a specified control. More control than if I had simply used XAML binding.
Thanks Clemens,
Dan

Check which submenu item was clicked in context menu strip

There is a ContextMenuStrip in a grid control.
I have named it as GridContextMenu.
The GridContextMenu is populated with 4 - 5 items using the following code :
gridcontextMenu.Items.Add(new ToolStripMenuItem
{
Name = Plants,
Text = Plants,
Tag = Plants,
Width = 100,
Image = <image source is put here>
});
gridcontextMenu.Items.Add(new ToolStripMenuItem
{
Name = Animals,
Text = Animals,
Tag = Animals,
Width = 100,
Image = <image source is put here>
});
For the animal menu in tool strip, i added submenu in the following way
(gridcontextMenu.Items[1] as ToolStripMenuItem).DropDownItems.Add("Tiger", image_source, new EventHandler(SubmenuItem_Click));
(gridcontextMenu.Items[1] as ToolStripMenuItem).DropDownItems.Add("Lion", image_source, new EventHandler(SubmenuItem_Click));
(gridcontextMenu.Items[1] as ToolStripMenuItem).DropDownItems.Add("Elephant", image_source, new EventHandler(SubmenuItem_Click));
In the SubmenuItem_Click event handler i need to know which animal submenu was clicked.
How to achieve this ?
currently i have the code for event handler in the following way :
private void SubmenuItem_Click(object sender, EventArgs e)
{
}
How to check condition in this event that which animal submenu was selected ?
Kindly share the answer.
You can do something like this:
private void SubmenuItem_Click(object sender, EventArgs e)
{
var clickedMenuItem = sender as MenuItem;
var menuText = clickedMenuItem.Text;
switch(menuText) {
case "Tiger":
break;
case "Lion":
break;
. ...
}
}
As I found that none of the other answers worked here, I went digging and found the proper solution. This may have been applicable only in .NET Framework 4+ but here is what I found to work.
Essentially, the ItemClicked event in the ContextMenuStrip control passes itself as the sender and a ToolStripItemClickedEventArgs object when the event is raised. As you can't obtain the clicked item from the ContextMenuStrip itself, the only way to obtain this information is to interrogate the ToolStripItemClickedEventArgs object and the clicked item resides in there as a ToolStripItem object. This can then be used to extract the name of the option to use in an if/switch statement as appropriate. See below:
To configure the EventHandler:
...
contextMenuStrip1.ItemClicked += OnContextMenuItem_Clicked;
...
To handle the event and retrieve the text of the clicked item:
private void OnContextMenuItem_Clicked(object sender, ToolStripMenuItemClickedEventArgs e)
{
ToolStripItem clickedItem = e.ClickedItem;
string itemName = clickedItem.Text;
...
}
Hopefully this helps someone looking for this answer in future :)
You can use Tag for this purpose in case when your should localize your application.
Moreover Tag is an object so you can put any tapy of data there. For example Enum type.
private void SubmenuItem_Click(object sender, EventArgs e)
{
var clickedMenuItem = sender as MenuItem;
EnumType item = (EnumType)clickedMenuItem.Tag;
switch(item) {
case TigeItem:
break;
case LionItem:
break;
...
}
}
This is a way to retrieve the ToolStripMenuItem's index if you have created the ContextMenuStrip Dynamically. It is really helpful with getting Enum values. My Context menu is dynamically created and filled with the Enum Names. I hope it helps someone. Sorry for the formatting still new to posting.
`private void DynamiallyCreatedContextMenu_Click(object sender, EventArgs e)
{
ToolStripMenuItem item = sender as ToolStripMenuItem;
var parent = (item.Owner as ContextMenuStrip);
for (int i = 0; i < parent.Items.Count; i++)
{
if (item == parent.Items[i])
{
index = i;
break;
}
}
}`
private void SubmenuItem_Click(object sender, EventArgs e)
{
string clickedItemName=e.ClickedItem.Text;
}

Categories

Resources