Updating a Listbox Automatically - c#

I have 2 listboxes. The first one is enabled and the second one is disabled. The second listbox will get its data from the first one.
For example, let's say I entered 2 in listbox1. listbox2 will get 2 + 1 = 3
Thing is, I want to update the second listbox automatically without clicking any button.
Is that even possible?
I wrote the following code in a button:
private void btnResult_Click(object sender, EventArgs e)
{
int WantedYear = Convert.ToInt32(txtForecastingYear.Text);
int FirstYearValue = WantedYear - 4;
txtFirstYear.Text = FirstYearValue.ToString();
int SecondYearValue = WantedYear - 3;
txtSecondYear.Text = SecondYearValue.ToString();
int ThirdYearValue = WantedYear - 2;
txtThirdYear.Text = ThirdYearValue.ToString();
int FourthYearValue = WantedYear - 1;
txtFourthYear.Text = FourthYearValue.ToString();
}
I want to do it without having to use a button to update. How can I do that?
Note: I'm using Windows Forms.

You can write your code in the SelectedIndexChanged event of the listbox. This event would be automatically fired as soon as the IndexChanges.
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
You can read more about it here.

Related

C# WinForms contextmenu focus issue when textbox is added

In a C# WinForms application I need to create a ContextMenuStrip with dropdown and textbox:
private System.Windows.Forms.ContextMenuStrip ct1;
private void button_Click(object sender, EventArgs e)
{
var header = new ToolStripMenuItem("Header");
header.Enabled = false;
var options = new ToolStripMenuItem("Options");
for (int i = 0; i < 5; i++)
{
var checkoption = new ToolStripMenuItem("Check Me " + i + "!");
checkoption.CheckOnClick = true;
options.DropDownItems.Add(checkoption);
}
var txt = new ToolStripTextBox();
txt.Text = "changeme";
options.DropDownItems.Add(txt);
options.DropDown.Closing += DropDown_Closing;
ct1.Items.Clear();
ct1.Items.Add(header);
ct1.Items.Add(options);
ct1.Show(this, button.Left, button.Top);
}
private void DropDown_Closing(object sender, ToolStripDropDownClosingEventArgs e)
{
e.Cancel = (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked);
}
Now, e.Cancel will prevent closing the dropdown if the reason is ItemClicked, so I can select more items without having to open the menu again:
Please note that "changeme" is a ToolStripTextBox!
Once I focus it (click on it), I can edit the text inside:
After finish editing the textbox, I still can change the checkbox items, but there is no focus indicator:
How can I get back the focus indicator just as shown on the first picure?
Note: if I move the mouse onto "Header", the dropdown will close, and then moving it back to "Options", will reopen the dropdown and then the focus indicator is good again:
How can I do this without closing and reopening the dropdown?
I have tried Select() for the options item, but it did not help, neither Invalidate() on ct1.
Just have found it:
First needs to add a click handler on the dropdown:
options.DropDown.Click += DropDown_Click;
Then in the click handler it needs to be focused:
private void DropDown_Click(object sender, EventArgs e)
{
var dropdown = (ToolStripDropDown)sender;
dropdown.Focus();
}

How to get a button to select a random name from a list

I have a list with names. These names are linked to a label. When I click the label a name at random designated for that label is selected.
What I need is for when a button is clicked, it selects a random name for each label.
for example;
I have 5 names in a list and each individual list is linked to an individual label. One name will be selected for a label at random. I need all 10 of my labels to select a random name, when a button is clicked.
Hope that makes sense. I am using Visual Studio 2010 and c# on a form. Many Thanks
So this is what I have. This is part of the code I need (dont worry with what its about). The goalkeeper label is called "goalkeeper" my button should be called "pickTeam" but when clicked shows up as "button1_Click" private void button1_Click(object sender, EventArgs e)
I need it so that when the button clicked, every label (I can do myself once figured out) will choose a random name that has been given. I.E; Begovic, De Gea etc etc.
i have a method for each position. This is the Goalkeeper, once I know this I can do it for the other positions. Thanks
private void goalkeeper_Click(object sender, EventArgs e)
{
Random rand = new Random();
List<string> goalkeepers = new List<string>();
goalkeepers.Add("Neuer");
goalkeepers.Add("De Gea");
goalkeepers.Add("Lloris");
goalkeepers.Add("Begovic");
for (int i = 0; i < 4; i++)
{
int index = rand.Next(0, 4);
goalkeeper.Text = goalkeepers[index];
}
}
Order your goalkeepers list by a new Guid to a get a random order, then pick the first:
private void SetLabelText(Label label, List<string> names)
{
var randomName = names.OrderBy(x => Guid.NewGuid()).FirstOrDefault();
label.Text = randomName;
}
You could call this for each of your labels e.g:
private void SetupLabels()
{
SetLabelText(label1, goalkeepers);
SetLabelText(label2, goalkeepers);
SetLabelText(label3, goalkeepers);
SetLabelText(label4, goalkeepers);
SetLabelText(label5, goalkeepers);
}
private void goalkeeper_Click(object sender, EventArgs e)
{
SetupLabels();
}
But to be honest, there isn't a lot wrong with what you already have

My form doesn't loop this correctly

I can't seem to get this loop to work.
Once the submit button is clicked ten times it should revert to the main form; instead it's reverting as soon as the submit is clicked once.
private void submit_Click(object sender, EventArgs e)
{
Form1 mainMenu = new Form1();
int repeat = 0;
do
{
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A1.secondRandomNumber().ToString();
repeat++;
} while (repeat <= 10);
if (repeat == 11)
{
mainMenu.Show();
this.Hide();
}
}
Everything inside of submit_Click occurs for each click. That includes defining repeat anew, setting it to 0, looping to increment it entirely to 11, and swapping which form is visible.
If you want to count the number of clicks, you'll have to establish your counter outside of the handler so it can be incremented:
private int repeatSubmit = 0;
private void submit_Click(object sender, EventArgs e)
{
if (repeatSubmit < 10)
{
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A1.secondRandomNumber().ToString();
repeatSubmit++;
}
else
{
mainMenu.Show();
this.Hide();
repeatSubmit = 0; // ready for the next time `this` form is shown
}
}
Just to clarify, you are waiting for the user to click the button 10 times? Or the loop is supposed to simulate 10 clicks?
This loop will enter (do) and set num1 and num2, add one to repeat, and then do that 10 times until repeat == 11, and then it will display the main menu.
I think the code you make be looking for is as follows:
private void submit_Click(object sender, EventArgs e)
{
...
repeat ++;
num1.Text = A1.firstRandomNumber().ToString();
num2.Text = A2.secondRandomNumer().ToString();
if(repeat >=10)
{
mainMenu.Show();
this.Hide();
}
}
As your code is, on 1 click you enter your loop where you proceed to increment the counter until it's equal to 11, then you exit your loop and show the main menu. Basically you're not counting clicks.
What you want to do is store the counter somewhere, probably as a class variable. Then every time you enter the click function you increment. When the click function has been entered 10 times then you would go into your if statement.
private int clickCount = 0;
private void submit_Click(object sender, EventArgs e){
clickCount++;
// Other code that happens on a click
if (clickCount == 10){ // 10th click show main menu
// Code to show main menu
}
}
It runs through the loop on the first click of submit, if I understand what you are trying to achieve, you don't need a loop at all, just a counter for each time the button is pressed.

Events and Buttons

I want to get the text of the button whenever I click on it.
The algorithm that I made is where i have a function that is a loop that creates a number of buttons and assigns numbers:
void ListAllPage()
{
if (pageMax < 50)
{
//if page max less than 50
for (int i = 0; i < pageMax; i++)
{
Button newBtn = new Button();
newBtn.Text = i.ToString();
newBtn.Width = 50;
newBtn.Click += page_Clicked;
pageCell.Controls.Add(newBtn);
}
}
}
Now buttons will appear on the screen, their events will be triggered and the function page_Click; will be executed:
public void page_Clicked(object sender, EventArgs e)
{
//inside this function I want to obtain the button number that was clicked by the user. How do I do that?
}
Take note, I must all the functions that I described here,...
My thinking is to feed all the buttons that i created inside the loop to a dictionary..
Dictionary.. it will take variables like this btndic.Add(Button b=new Button,b.text);
But the issue is how to retrieve the buttons,,,
if there is a better way, i would like to hear about it...
instead of using the Click Event -> Use the Command Event: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.oncommand.aspx then you can distinguish which button has been clicked
You just need to cast the sender object to a Button, or more generally, a Control:
public void page_Clicked(object sender, EventArgs e)
{
Control c = sender as Control;
MessageBox.Show("Clicked on " + c.Text);
}
Also, it might be more appropriate to use the Tag property to store your custom information (number). In that case, Text property can be anything you like.
Try this way
public void page_Clicked(object sender, EventArgs e)
{
Button btn=(Button)sender;
}
in your ListAllPage method assign Tag to each button:
newBtn.Tag = i;
In your handler you can obtain button instance from sender:
var clickedButton = (Button)sender;
int pageIndex = (int)clickedButton.Tag;

Keep selection when clicking into textbox

I need to have the text in a TextBox become selected when a user clicks into the box. If the text is already selected, it needs to be a regular cursor. So on the click event of all the textboxes I have this code:
TextBox t = (TextBox)sender;
bool alreadyselected = t.SelectedText == t.Text;
if (!alreadyselected) t.SelectAll();
the problem is, by the time the click event is reached, t.SelectedText is empty
so the full text always becomes selected even when clicking multiple times
I would appreciate a solution that can be for all the textboxes at once if possible
You're correct, the default Click for the TextBox is changing the position of the caret and thus clearing any selected text. But you can restore it.
First add 2 int vars to store the selection Start and Length and initialize Start as -1 to signal not set:
private int SelectedStart = -1;
private int SelectedLength = 0;
then make a handler for the TextBox's Leave event and save the Start and Length for the currently selected text when we lose focus.
private void textBox1_Leave (object sender, EventArgs e)
{
SelectedStart = textBox1.SelectionStart;
SelectedLength = textBox1.SelectionLength;
}
Finally, make a handler for the TextBox's Click event and, if we previously saved the Start and Length, restore them to the TextBox and then set Start to -1 to signal not set again (this allows for normal click behavior within textbox when it is focused).
private void textBox1_Click (object sender, EventArgs e)
{
if (SelectedStart != -1) {
textBox1.SelectionStart = SelectedStart;
textBox1.SelectionLength = SelectedLength;
SelectedStart = -1;
}
}
Use the Control.Tag property to set a bool flag to select or deselect the TextBox text:
private void TextBox_Click(object sender, EventArgs e)
{
TextBox txtBox = (TextBox)sender;
txtBox.SelectionStart = 0;
// First click will select the text
if (txtBox.Tag == null)
{
txtBox.Tag = true;
txtBox.SelectionLength = txtBox.Text.Length;
}
// Second click will deselect the text
else
{
txtBox.Tag = null;
txtBox.SelectionLength = 0;
}
}

Categories