I have a listbox displaying items from an enum. I want to select/highlight the current value (read from a database) when the listbox displays/the form opens. This code, though:
lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(lblSelectedPrinter.Text);
...does not work. I saw an example using "GetItemAt" here (Programmatically selecting Items/Indexes in a ListBox) but my stripped down and archaic version of C# (.NET 1.1, C# 2) has no such critter.
UPDATE
I thought this would work:
string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
lblSelectedPrinter.Text = currentPrinter;
int currentPrinterIndex = listBoxBeltPrinters.Items.IndexOf(currentPrinter);
listBoxBeltPrinters.SelectedItem = currentPrinterIndex;
...but it, also, does not (the current printer displays in the label, but the corresponding entry/value in the listbox is not selected).
I see you've already solved this, but why not do it the tried and tested way?
lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");
listBoxBeltPrinters.SelectedIndex = -1;
if (!String.IsNullOrEmpty(lblSelectedPrinter.Text)) {
for (int index = 0; index < listBoxBeltPrinters.Items.Count; index++) {
string item = listBoxBeltPrinters.Items[index].ToString();
if (lblSelectedPrinter.Text == item) {
listBoxBeltPrinters.SelectedItem = index;
break;
}
}
}
This way, you know the SelectedIndex value is set to -1 as soon as the text changes, and if it is found in your ListBox, that item is selected.
Even better would be to write a handler when the Label control lblSelectedPrinter fires the TextChanged event.
lblSelectedPrinter.TextChanged += new EventHandler(SelectedPrinter_TextChanged);
Then, create that Event Handler like shown above:
private void SelectedPrinter_TextChanged(object sender, EventArgs e) {
listBoxBeltPrinters.SelectedIndex = -1;
if (!String.IsNullOrEmpty(lblSelectedPrinter.Text)) {
for (int index = 0; index < listBoxBeltPrinters.Items.Count; index++) {
string item = listBoxBeltPrinters.Items[index].ToString();
if (lblSelectedPrinter.Text == item) {
listBoxBeltPrinters.SelectedItem = index;
break;
}
}
}
}
You've already solved your problem, so this is just food for thought.
This works:
listBoxBeltPrinters.SetSelected(listBoxBeltPrinters.FindString("beltprinter"), true);
int i = AppSettings.ReadSettingsVal("beltprinter"); //Save it as an int.
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(i);
lblSelectedPrinter.Text = listBoxBeltPrinters.SelectedItem.toString();
You need it to be an integer. You can use int.Parse to Convert to cast it from string to int.
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.IndexOf(int.Parse(System.Configuration.ConfigurationSettings.AppSettings.Get("beltprinter")));
lblSelectedPrinter.Text = listBoxBeltPrinters.SelectedItem.toString();
This works:
string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
lblSelectedPrinter.Text = currentPrinter;
int currentPrinterIndex = listBoxBeltPrinters.Items.IndexOf(currentPrinter);
listBoxBeltPrinters.SelectedIndex = currentPrinterIndex;
This is the only code required to display, read, and write the settings val:
private void PrinterPickerForm_Load(object sender, System.EventArgs e)
{
Type type = typeof(PrintUtils.BeltPrinterType);
foreach (FieldInfo field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
{
string display = field.GetValue(null).ToString();
listBoxBeltPrinters.Items.Add(display);
}
string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
lblCurrentPrinter.Text = currentPrinter;
int currentPrinterIndex = listBoxBeltPrinters.Items.IndexOf(currentPrinter);
listBoxBeltPrinters.SelectedIndex = currentPrinterIndex;
}
private void btnSaveSelectedVal_Click(object sender, System.EventArgs e)
{
string sel = listBoxBeltPrinters.SelectedItem.ToString();
if (sel != lblCurrentPrinter.Text)
{
AppSettings.WriteSettingsVal("beltPrinter", sel);
}
}
can you try the following??? It takes from your code, and then uses FindString
string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
lblSelectedPrinter.Text = currentPrinter;
int index = listBoxBeltPrinters.FindString(lblSelectedPrinter.Text);
listBoxBeltPrinters.SelectedIndex = index;
Combination of listBoxObject.SetSelected() and listBoxObject.FindString() is an elegant solution. It works for me, too.
lblSelectedPrinter.Text = AppSettings.ReadSettingsVal("beltprinter");
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.FindByText(lblSelectedPrinter.Text);
By value:
listBoxBeltPrinters.SelectedItem = listBoxBeltPrinters.Items.FindByValue(1);
Related
new to WPF so not sure if there is some sort of syntax that I am missing or what.
Course choice;
int totalCredits = 0;
int classesRegistered = 0;
string[] registeredCourses = new string[3];
private void button_Click(object sender, RoutedEventArgs e)
{
if (classesRegistered < 3)
{
choice = (Course)(this.comboBox.SelectedItem);
if ((!choice.Equals(registeredCourses[0]))
&& (!choice.Equals(registeredCourses[1]))
&& (!choice.Equals(registeredCourses[2])))
{
registeredCourses[classesRegistered] = choice.ToString();
this.listBox.Items.Add(registeredCourses[classesRegistered]);
classesRegistered = classesRegistered + 1;
}
}
}
So I don't want the choice to be added to the listbox if its already registered to one of the array's values. What is it I'm missing?
Your if statement is comparing a string to a Course object, you may change it to below:
if(!registeredCourses.Any(obj=> obj.Equals(choice.ToString())))
I have created a method that allows me to find the next empty Box:
public int CheckBox(int boxNum) {
int BoxNumber = 0;
TextBox[] itemBoxArray = new TextBox[] { itemBox0, itemBox1, itemBox2, itemBox3, itemBox4, itemBox5, itemBox6, itemBox7,
itemBox8, itemBox9,itemBox10,itemBox11,itemBox12,itemBox13,itemBox14,itemBox15,};
for (int i = 0; i < itemBoxArray.Length; i++)
{
if (String.IsNullOrEmpty(itemBoxArray[i].Text))
{
BoxNumber = i;
i = 15;
}
}
return BoxNumber;
}
Next i created a button to check what the empty box is and i would like to input something into this box but i cannot find a way ro convert the string that carries the empty box number to that text box:
private void StandAroundRebar_Click(object sender, EventArgs e)
{
int emptybox = CheckBox(0);
string emptyboxString = emptybox.ToString();
string newbox = "itemBox" + emptyboxString;
MessageBox.Show("TextBox # " + newbox + " is empty ");
var textbox = this.Controls.Find(newbox, true);
}
}
}
Well, I would rather change the CheckBox method
public TextBox CheckBox() {
var itemBoxArray = new TextBox[] { itemBox0, itemBox1, itemBox2, itemBox3, itemBox4, itemBox5, itemBox6, itemBox7,
itemBox8, itemBox9,itemBox10,itemBox11,itemBox12,itemBox13,itemBox14,itemBox15,};
return itemBoxArray.First(m => string.IsNullOrEmpty(m.Text));//or FirstOrDefault
}
now you would get a TextBox returned, and could do whatever you want with it.
You need this function:
http://msdn.microsoft.com/de-de/library/486wc64h(v=vs.110).aspx
This will find it, all you have to do is casting it.
Then:
BoxNumber = i;
i = 15;
What should that do? You set the i to the box number and then you set it again to 15?!
That isn't supposed to work.
Why not just return the TextBox object directly?
public TextBox GetNextEmptyTextBox()
{
return (new[] { textBox1, textBox2, textBox3 })
.FirstOrDefault(tb => string.IsNullOrEmpty(tb.Text));
}
You need Control.ControlCollection.Find and than a cast to TextBox.
TextBox newBox = this.Controls.Find("itemBox1", true).FirstOrDefault() as TextBox;
Once you find your Box you can set the text:
newBox.Text = "my text";
I have a combobox , bound to Datatable
and have the following properties:
cboCars.DisplayMember = "carLiscen";
cboCars.ValueMember = "carNo";
How can I select the DisplayMember when I know the ValueMember ?
If you have a ValueMember set you can select using SelectedValue
cboCars.DisplayMember = "carLiscen";
cboCars.ValueMember = "carNo";
cboCars.SelectedValue = "valuemember value";
You can use cboCars.SelectedValue = "123"; property for this. Here's a code snippet which will show it in action.
public void Test()
{
ArrayList info = new ArrayList();
info.Add(new CarInfo { CarLiscen = 123456, CarNo = 123});
info.Add(new CarInfo { CarLiscen = 234567, CarNo = 234 });
cboCars.DataSource = info;
cboCars.DisplayMember = "CarLiscen";
cboCars.ValueMember = "CarNo";
cboCars.SelectedValueChanged +=
delegate(object sender, EventArgs e)
{
if (cboCars.SelectedIndex != -1)
{
this.Text = cboCars.SelectedValue.ToString();
}
};
cboCars.SelectedValue = 234;
}
And if you wonder what is the definition of CarInfo. Here's its code (which is fairly simple):
public class CarInfo
{
public int CarLiscen { get; set; }
public int CarNo { get; set; }
}
Hope this helps.
You can search for the correct item and set it to that, very simple:
cbTEST.SelectedIndex = cbTEST.FindStringExact("your search string here");
or select an item based on an ListViewItem:
cbTEST.SelectedIndex = cbTEST.FindStringExact(lvTEST.SelectedItems[0].SubItems[0].Text);
thats it. very simple!
Hi Guys the best way if searching for a text or value
is
int Selected;
int count = ComboBox1.Items.Count;
for (int i = 0; (i<= (count - 1)); i++)
{
ComboBox1.SelectedIndex = i;
if ((string)(ComboBox1.SelectedValue) == "SearchValue")
{
Selected = i;
}
}
ComboBox1.SelectedIndex = Selected;
The problem is that the combobox expect the exact type.
So if you for example use a datagridview and you see the value (int) in the field, you pass it to the SelectedValue property of the combo. But in fact you are not passing an integer, you are passing an object. That is what usually is going wrong. It my a while to sort this out, but finally I have found how to do it...
How to solve this... easy:
For example, you have an ID (integer in the database), then you need to do something like this:
This is the one that I did and it does not work:
cmbFilter.SelectedValue = dgvListOfFilters.Rows[intRowSelected].Cells[3].Value;
You should do this to make it work:
int intCategory = Convert.ToInt32(dgvListOfFilters.Rows[intRowSelected].Cells[3].Value);
cmbFilter.SelectedValue = intCategory;
Hope this will be helpfull for many people...
I want to add "," to after every group of 3 digits. Eg : when I type 3000000 the textbox will display 3,000,000 but the value still is 3000000.
I tried to use maskedtexbox, there is a drawback that the maskedtexbox displayed a number like _,__,__ .
Try adding this code to KeyUp event handler of your TextBox
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("en-US");
int valueBefore = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
textBox1.Text = String.Format(culture, "{0:N0}", valueBefore);
textBox1.Select(textBox1.Text.Length, 0);
}
}
Yes, it will change the value stored in a texbox, but whenever you need the actual number you can use the following line to get it from the text:
int integerValue = Int32.Parse(textBox1.Text, System.Globalization.NumberStyles.AllowThousands);
Of course do not forget to check that what the user inputs into the textbox is actually a valid integer number.
Use String.Format
int value = 300000
String.Format("{0:#,###0}", value);
// will return 300,000
http://msdn.microsoft.com/en-us/library/system.string.format.aspx
This may work fine for your scenario I hope.
private string text
{
get
{
return text;
}
set
{
try
{
string temp = string.Empty;
for (int i = 0; i < value.Length; i++)
{
int p = (int)value[i];
if (p >= 48 && p <= 57)
{
temp += value[i];
}
}
value = temp;
myTxt.Text = value;
}
catch
{
}
}
}
private void digitTextBox1_TextChanged(object sender, EventArgs e)
{
if (myTxt.Text == "")
return;
int n = myTxt.SelectionStart;
decimal text = Convert.ToDecimal(myTxt.Text);
myTxt.Text = String.Format("{0:#,###0}", text);
myTxt.SelectionStart = n + 1;
}
Here, myTxt = your Textbox. Set Textchanged event as given below and create a property text as in the post.
Hope it helps.
You could hook up to OnKeyUp event like this:
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (!(e.KeyCode == Keys.Back))
{
string text = textBox1.Text.Replace(",", "");
if (text.Length % 3 == 0)
{
textBox1.Text += ",";
textBox1.SelectionStart = textBox1.Text.Length;
}
}
}
Get Decimal Value Then set
DecimalValue.ToString("#,#");
Just learning C# (along with object and event programing) and the teacher didn't really show us how to get things done.
class Postion
{
private int[] x_coordinate = new int[100];
private int[] y_coordinate = new int[100];
private double[] speed = new double[100];
private int[] direction = new int[100];
const int MAX_SPEED = 50;
int counter = 0;
public Postion()
{
x_coordinate[counter] = 0;
y_coordinate[counter] = 0;
speed[counter] = 0;
direction[counter] = 0;
}
//get set methods
public int X
{
get
{
return x_coordinate[counter];
}
set
{
x_coordinate[counter] = value;
}
}
There is one more Class between them
The values are frist assigned by a button click.
Airplane newplane = new Airplane();
private void BtnCreate_Click(object sender, EventArgs e)
{
bool box = txtName.Text != "";
if (box == true)
newplane.Name = txtName.Text;
else { }
box = txtx.Text != "";
if (box == true)
newplane.PlanePostion.X = int.Parse(txtx.Text);
else { }
Etc.
I can call on the array values for display for the list box.
private void lsbplanes_SelectedIndexChanged(object sender, EventArgs e)
{
placeholder = newplane.PlanePostion.Counter;
newplane.PlanePostion.Counter = lsbplanes.SelectedIndex;
if (newplane.PlanePostion.Counter < 0)
newplane.PlanePostion.Counter = 0;
else { }
lblxshow.Text = Convert.ToString(newplane.Getx());
but when using a destroy button to remove an item in the list box I need to have it so the box updates with the new values when the user selects the item in the listbox.
This is what I have to try and do it so far, it sets all the ones above to 0s but does remove the the deleted one fine
private void BtnKill_Click(object sender, EventArgs e)
{
if (lsbplanes.SelectedIndex == -1)
{
MessageBox.Show("Please select an item first.", "No item selected", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
placeholder = lsbplanes.SelectedIndex;
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
while (newplane.PlanePostion.Counter > placeholder)
{
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter--;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
}
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);
newplane.PlanePostion.Counter = lsbplanes.Items.Count;
}
anyone can help me on this?
I was torn in this question, answer exactly what your problem is, or suggest that you redesign it.
#Marc is right you should be using some sort of List<Position> on your Plane object (or a ReadOnlyObservableCollection<Position>).
#Marc is also right, that the problem you are having is that you are trying to push the values down from the end of the list and overwriting them. In these cases it is better to start from the deletion point and pull them down.
So if you have {1,2,3,4,5,6,7,8,9,10} and you delete from item 5, you would have {1,2,3,4,10,10,10,10,10,10}. The code below will let you end up with {1,2,3,4,6,7,8,9,0}
placeholder = lsbplanes.SelectedIndex;
int idx = placeholder;
while (idx < lsbplanes.Items.Count)
{
newplane.PlanePosition.Counter = idx+1;
placex = newplane.PlanePostion.X;
placey = newplane.PlanePostion.Y;
placespeed = newplane.Getspeed();
placedic = newplane.Getdirection();
newplane.PlanePostion.Counter = idx;
newplane.PlanePostion.X = placex;
newplane.PlanePostion.Y = placey;
newplane.PlanePostion.Speed = placespeed;
newplane.PlanePostion.Direction = placedic;
idx++;
}
// Need to zero out elements at the end
newplant.PlanePosition.Counter = lsbplanes.Items.Count;
/* Zeroing code goes here */
newplane.PlanePosition.Counter = placeholder;
lsbplanes.Items.RemoveAt(lsbplanes.SelectedIndex);