I have Label on my Form, for example:
lblUser.Text = "John";
I need the text to change when user clicks on it
private void lblUser_Click(object sender, EventArgs e)
{
lblUser.Text = "Mike";
}
So if user clicks again, the text should changes back. How I can switch this text unlimited number of times? Count of names can be more than 2.
Text should be changed
John -> Mike -> Jack -> John -> Mike -> Jack -> John -> ...
and so on.
First, let's organize available names into a collection (let it be an array):
private static string[] s_Names = new [] {
"John", "Mike", "Jack", "Thomas",
};
then we can change name on Click with a help of Linq:
using System.Linq;
...
private void lblUser_Click(object sender, EventArgs e) {
lbUser.Text = s_Names
.SkipWhile(name => name != lbUser.Text) // scroll up to the current name
.Skip(1) // skip current name
.FirstOrDefault() ?? s_Names.First(); // restart if s_Names is exhausted
}
Edit: Same idea, no Linq solution (we are looking for index of current name add 1 and use modulo arithmetics to restart the sequence of names)
private void lblUser_Click(object sender, EventArgs e) {
lbUser.Text = s_Names[(Array.IndexOf(s_Names, lbUser.Text) + 1) % s_Names.Length];
}
Use an array to store the Names you want it to switch from (Or list if you want to add items at runetime):
private string[] Names = new string[]{"John","Mike"}; //Etc.
Now you want to store which name is being shown with an index:
private int NameIndex = 0;
Finally, you can iterate through the array whenever the button is clicked:
private void lblUser_Click(object sender, EventArgs e)
{
lblUser.Text = Names[NameIndex%Names.Length];
NameIndex++;
}
If you have just two names that you want to switch you can do the bellow:
class Program {
private const string nameOne = "John";
private const string nameTwo = "Mike";
private void lblUser_Click (object sender, EventArgs e) {
if (lblUser.Text == nameOne)
{
lblUser.Text = nameTwo;
}else{
lblUser.Text = nameOne;
}
}
}
int nameCounter = 0; // Variable to track displayed element
var usernameList = new List<string> { "John", "Mike", "Bill", "Andy" }; // list of values to cycle
lblUser.Text = usernameList[nameCounter++];
private void lblUser_Click(object sender, EventArgs e)
{
nameCounter = nameCounter < usernameList.Count ? nameCounter : 0;
lblUser.Text = usernameList[nameCounter++];
}
checking the label and changing it based on the requirement.
private void button1_Click(object sender, EventArgs e)
{
int index = names.IndexOf(label1.Text);
index = (index + 1) % (names.Count);
label1.Text = names[index];
}
Related
So I have 2 list boxes within my form. Listbox1 contains different types of items that have a price and Listbox2 contains how much of that item you want to purchase. How do I update my price label so when I select both options from each list box it updates the label and gives me a price. Here's an example to help you better understand.
I select the $1.50 Chocolate Chip Cookie item in my ListBox1 and in ListBox2 I select the 1 Dozen Cookie item. So I would want my priceLabel to update to $18.00. How would I do this?
As of now I have tried creating some code in the listBox1_SelectedIndexChanged method but I am returned these 3 following values... $0.00...$2.00...$4.00
Here's my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
double index = listBox1.SelectedIndex;
double index2 = listBox2.SelectedIndex;
double total = index * index2;
label9.Text = total.ToString("C");
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label9_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
{
const int ESTIMATED_ARRIVAL = 3;
label10.Text = monthCalendar1.SelectionStart.AddDays(ESTIMATED_ARRIVAL).ToShortDateString();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
In listBox1_SelectedIndexChanged(object sender, EventArgs e) you use listBox1.SelectedIndex; and listBox2.SelectedIndex;, if you refer to ListBox.SelectedIndex Property
ListBox.SelectedIndex Property
Gets or sets the zero-based index of the currently selected item in a
ListBox.
Property Value
Int32
A zero-based index of the currently selected item. A value of negative one (-1) is returned if no item is selected.
it just return index of selected item, so for your purpose you must get value of selected item.
I hope this code be a good guide for you:
Add handler of SelectedIndexChanged event of both list boxes to this method:
private void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.listBox1.SelectedIndex > -1 && this.listBox2.SelectedIndex > -1)//You can set default SelectedIndex for list boxes and remove this
{
string s1 = this.listBox1.Items[this.listBox1.SelectedIndex].ToString();
string s2 = this.listBox2.Items[this.listBox2.SelectedIndex].ToString();
//Now we extracting the number from string
//NOTE this is a simple implementation. You must change it as your needs.
//for example
//s1 = $1.50 Chocolate Chip Cookie
//s2 = 1 Dozen Cookie
int index = s1.IndexOf(' ');//get the index of first space after 1.50 (Number) in s1
s1 = s1.Substring(1, index);
index = s2.IndexOf(' ');//get the index of first space after 1 (Number) in s2
s2 = s2.Substring(0, index);
if (double.TryParse(s1, out double p1) && double.TryParse(s2, out double p2))
{
const int DOZEN = 12;
double result = p1 * (p2 * DOZEN);
//or
//remove const int DOZEN = 12; and simply
//double result = p1 * (p2 * 12);
this.label9.Text = result.ToString("C");
}
else
{
MessageBox.Show("Can not parse double values.");
}
}
}
I have 3 button. There are prev, next and add. i have a text file with 6 lines.
So as the form load, it's only display 3 lines ascending text, the other 3 lines is appear when i click next button. But i don't know how to make it appear.
This is my next button code
private void next_Click(object sender, EventArgs e)
{
string[] baca;
baca = System.IO.File.ReadAllLines(#path.Text);
nama.Text = baca[3];
npm.Text = baca[4];
alamat.Text = baca[5];
}
I want it to display another next lines with only 1 next button.
You need to store the current line in a variable so that when you click in buttons you can use this variable as reference.
Another thing, instead of setting the fixed indexes set a var as code below.
Ps: If you are using web plataform storage the current item in a hidden field.
private int i = 0; // or in hidden field
private void next_Click(object sender, EventArgs e)
{
string[] baca;
baca = System.IO.File.ReadAllLines(#path.Text);
nama.Text = baca[i];
npm.Text = baca[i+1];
alamat.Text = baca[i+2];
}
The answer has already been stated by #Plutonix, and I quote "Read the data once and use a form level var to index what to show."
int firstIndex = 0;
var baca = System.IO.File.ReadAllLines(#path.Text).ToList();
private void next_Click(object sender, EventArgs e)
{
firstIndex++;
nama.Text = baca[firstIndex];
npm.Text = baca[firstIndex + 1];
alamat.Text = baca[firstIndex + 2];
}
However, if you don't want a form level variable for some reason this would work:
private void next_Click(object sender, EventArgs e)
{
var baca = System.IO.File.ReadAllLines(#path.Text).ToList();
int firstIndex = 1 + baca.FindIndex(nama.Text);
nama.Text = baca[firstIndex];
npm.Text = baca[firstIndex + 1];
alamat.Text = baca[firstIndex + 2];
}
Remember, this is not the best way, and will not work if there are duplicates.
I want to update comboBox selectedItem name by changing textbox name. Without losing combobox value, How can I achieve it?
private void addItem_Click(object sender, EventArgs e)
{
nameItem.Enabled = true;
nameItem.Text = "Item " + counter.ToString();
nameItem.Focus();
comboBox1.Items.Add(nameItem.Text);
comboBox1.SelectedItem = nameItem.Text;
counter++;
}
private void nameItem_TextChanged(object sender, EventArgs e)
{
????????
}
This one is simple and it's working, but it maybe a little bit long.
Here I got a combo box, textBox1 and button for adding value to combo box,
and textBox2 for editing selected item.
string[] items = new string[99];
int a = 0;
int i = 0;
private void button1_Click(object sender, EventArgs e)
{
items[i] = textBox1.Text;
i++;
comboBox1.Items.Clear();
for (int n = 0; n < items.Length; n++) {
if(items[n] != null) comboBox1.Items.Add(items[n]);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
a = comboBox1.SelectedIndex;
MessageBox.Show(a.ToString());
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
items[a] = textBox2.Text;
comboBox1.Items.Clear();
for (int n = 0; n < items.Length; n++)
{
if (items[n] != null) comboBox1.Items.Add(items[n]);
}
}
How it works: we have an array for items and two integar variables. one for count of added items and other for selected Items index
Button 1 just addes new item, clears all items and update em again
when u edit text of textbox2, It will update items from 'items' array, and then update the combo box, ez
EDIT: Did not see winform tag - this will not work - will leave in case any ASP people come across.
public void TextBox1_OnTextChanged(object sender, EventArgs e)
{
ddl.DataSource = null;
ddl.DataBind();
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataSource = (from ListItem b in ddl.Items
select b.Selected ? new ListItem(TextBox1.Text, b.Value) : b).ToList();
ddl.DataBind();
}
ddl is name of the dropdown box
Textbox1 is the name of the textbox.
This will change the name of the selected item. If you need more code let me know in comments.
Thank you for your time and kind answers.
I solved the problem as it looks below;
private void addItem_Click(object sender, EventArgs e)
{
nameItem.Enabled = true;
comboBox1.Items.Add("Item " + counter.ToString());
comboBox1.SelectedItem = "Item " + counter.ToString();
nameMacro.Text = "Item " + counter.ToString();
//comboBox1.SelectedItem = nameItem.Text;
//nameItem.Focus();
// Ad degistirme -> comboBox1.Items[comboBox1.FindStringExact("string value")] = "New Value";
counter++;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
comboBox1.Items[comboBox1.SelectedIndex] = nameItem.Text;
}
it's better to update the source then bind it again.
try this also
private void nameItem_TextChanged(object sender, EventArgs e)
{
string value = nameItem.Text;
var list = (List<KeyValuePair<String, String>>)comboBox1.DataSource;
list.Add(new KeyValuePair<string, string>(value,value));
comboBox1.DataSource = list;
comboBox1.DataBind();
}
I want to remove the last character someone types in a textbox.
For example if someone types in an empty textbox "abcd", i want to remove the letter "d", or if in a textbox containing "abcd", the user types a 1 like in here: "ab1cd", i want to remove that 1
Listen to the TextChanged event of the textbox, and save the change that happened:
public partial class MainWindow : Window
{
private ICollection<TextChange> _latestChange = null;
public MainWindow()
{
InitializeComponent();
myTextBox.TextChanged += (o, a) =>
{
_latestChange = a.Changes;
};
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (_latestChange != null)
{
var change = _latestChange.FirstOrDefault(); // Just take first change
if (change.AddedLength > 0) // If text was removed, ignore
{
myTextBox.Text = myTextBox.Text.Remove(change.Offset, change.AddedLength);
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
string newstring = textBox1.Text;
for(int i = 0; i<=9; i++)
{
if(newstring.Contains(i.ToString()))
{
int start = newstring.IndexOf(i.ToString());
newstring = newstring.Remove(start, 1);
}
}
textBox1.Text = newstring.Remove(newstring.Length - 1);
}
This will remove the last letter and any kind of number in the string. Hope it helps.
I am new at C# and it seems the following code below does not seem to select my combobox value:
private void button1_Click(object sender, EventArgs e)
{
cbPortNumber.SelectedValue = 3;
or
cbPortNumber.setValue("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.FindString("3");
or
cbPortNumber.SelectedIndex = cbPortNumber.Items.IndexOf(cbPortNumber.Items.FindByValue("HDMI 4"));
}
The dropdown looks like this:
All code above does not seem to select HDMI 4 on the list... I dont have any errors but i also don't have it being selected.
Any help would be great!
update showing combobox
UPDATE 2
//
// cbPortNumber
//
this.cbPortNumber.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Append;
this.cbPortNumber.Enabled = false;
this.cbPortNumber.FormattingEnabled = true;
this.cbPortNumber.Location = new System.Drawing.Point(174, 40);
this.cbPortNumber.Name = "cbPortNumber";
this.cbPortNumber.Size = new System.Drawing.Size(133, 21);
this.cbPortNumber.TabIndex = 11;
this.cbPortNumber.Text = "global_hdmi_port";
this.helpPortNumber.SetToolTip(this.cbPortNumber, "The HDMI port number, to which you connected your USB-CEC adapter.");
this.cbPortNumber.SelectedIndexChanged += new System.EventHandler(this.cbPortNumber_SelectedIndexChanged);
#region Global settings
public CECSettingByte HDMIPort
{
get
{
if (!_settings.ContainsKey(KeyHDMIPort))
{
CECSettingByte setting = new CECSettingByte(KeyHDMIPort, "HDMI port", 1, _changedHandler) { LowerLimit = 1, UpperLimit = 15, EnableSetting = EnableHDMIPortSetting };
setting.Format += delegate(object sender, ListControlConvertEventArgs args)
{
ushort tmp;
if (ushort.TryParse((string)args.Value, out tmp))
args.Value = "HDMI " + args.Value;
};
Load(setting);
_settings[KeyHDMIPort] = setting;
}
return _settings[KeyHDMIPort].AsSettingByte;
}
}
Update 3
And this is what fires the action after selecting something in that dropdown:
private void OnSettingChanged(CECSetting setting, object oldValue, object newValue)
{
if (setting.KeyName == CECSettings.KeyHDMIPort)
{
CECSettingByte byteSetting = setting as CECSettingByte;
if (byteSetting != null)
{
if (!Settings.OverridePhysicalAddress.Value)
Config.HDMIPort = byteSetting.Value;
CECActions.SetConnectedDevice(Settings.ConnectedDevice.Value, byteSetting.Value);
}
}
So this code is working fine for me:
private void button1_Click(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 2;
}
you can not access a ItemSource if there are no items to access. The simple way is to Init the items over the Desinger
( Sory for the nonlocalized IDE ) than you can set the Property SelectedIndex to a Index that exits. The other way is to Add all HDMI items with the Combobox1.Items.Add function.
If you ever used Forms in VB ... its still the same
public Form1()
{
InitializeComponent();
var hdmi = "HDMI";
for (int i = 1; i < 15; i++)
{
comboBox1.Items.Add( hdmi + i);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.Items.Count >= 2)
comboBox1.SelectedIndex = 2;
}