I am aware of the question asked by user ElPeta. However the selected answer to his question does not fix my issue.
In my program I have a list box, whenever a check box is clicked and its checked property set to true, the list box is populated with text, however when the check box is unchecked, I want to remove the text associated with the check box from the list box.
Example Before and After:
My Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CarFinderByMake
{
public partial class frmCFBM : Form
{
public frmCFBM()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'honestRalphsUsedCarsDataSet.tblCars' table. You can move, or remove it, as needed.
this.tblCarsTableAdapter.Fill(this.honestRalphsUsedCarsDataSet.tblCars);
}
private void chkFord_CheckedChanged(object sender, EventArgs e)
{
if (chkFord.Checked)
{
//lstCarMakes.Items.Clear();
//populating the listbox
var fordCars = from x in honestRalphsUsedCarsDataSet.tblCars where x.Make.StartsWith("Ford") select x;
foreach (var x in fordCars)
{
lstCarMakes.Items.Add(x.ModelYear + " " + x.Make + " - " + x.Color);
}
}
else
{
for (int x = 0; x <= lstCarMakes.Items.Count; ++x )
{
//here I was attempting to find the index of the items...
if (lstCarMakes.Items.Contains("Ford"))
{
lstCarMakes.Items.IndexOf("Ford");
//and after that I was going to remove the items.
}
}
}
}
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked)
{
//lstCarMakes.Items.Clear();
//populating the list box
var cadillacCars = from x in honestRalphsUsedCarsDataSet.tblCars where x.Make.StartsWith("Cadillac") select x;
foreach (var x in cadillacCars)
{
lstCarMakes.Items.Add(x.ModelYear + " " + x.Make + " - " + x.Color);
}
}
}
}
}
The ListBox.ObjectCollection returned from ListBox.Items has methods Remove(obj) and RemoveAt(index). You can loop it backwards and use RemoveAt:
private void chkFord_CheckedChanged(object sender, EventArgs e)
{
if (chkFord.Checked)
{
// you have it working ...
}
else
{
for (int x = lstCarMakes.Items.Count - 1; x >= 0; x-- )
{
string car = lstCarMakes.Items[x].ToString();
if(car.IndexOf("Ford", StringComparison.InvariantCultureIgnoreCase) >= 0)
lstCarMakes.Items.RemoveAt(x);
}
}
}
I have also used String.IndexOf instead of Contains to support case-insensitivity.
I don't know your specific error, but I imagine you might have an issue since you're using the item count of the listbox, and removing the items. When the item gets deleted the item count is changed. I believe there's a method for list box such as listbox.BeginUpdate() you can call before making changes to the items within the listbox and listbox.Update() after you're finished. Let me know if I'm in the right area with your problem
Related
so the assignment is to read from the student file into an array and read into the answer key array, compare the two and output a grade based on the array comparison.
the issue i'm having is that when i try to load the answer key into it's array it's like its not even getting the data, because all the questions output as wrong.
below is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AshleyBrown_CPT185A01S_Chapter7Lab
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//variables
private const int SIZE = 20; //current # of q's on test
private int index = 0, count = 1; //counter variables
private int wrong = 0, right = 0; //grade variables
these are the arrays that are used for the answers:
//arrays
private char[] studentAnswers = new char[SIZE];
private char[] answerKey = new char[SIZE];
private void calculateBtn_Click(object sender, EventArgs e)
{
//prevents any file errors
try
{
ReadStudentFile();
ReadAnswerKey();
CompareAnswers();
}
catch
{
MessageBox.Show("File doesn't exist or has the wrong name.");
}
}
private void clearBtn_Click(object sender, EventArgs e)
{
//Clear Form
studentAListBox.Items.Clear();
correctAListBox.Items.Clear();
wrongAListBox.Items.Clear();
incorrectBox.Text = "";
correctBox.Text = "";
percentBox.Text = "";
}
private void exitBtn_Click(object sender, EventArgs e)
{
//close program
Close();
}
method for reading the student file that works:
private void ReadStudentFile()
{
//Stream Reader Setup
StreamReader studentFile;
studentFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Student File.txt");
//Read Student Answers into studentAnswers Array
while (index < studentAnswers.Length && !studentFile.EndOfStream)
{
studentAnswers[index] = char.Parse(studentFile.ReadLine());
index++;
}
//Close Student Answer file
studentFile.Close();
//Display Student Answers
foreach (char answer in studentAnswers)
{
studentAListBox.Items.Add(count + ". " + answer.ToString());
count++;
}
}
method for reading answer key that populates with no data:
private void ReadAnswerKey()
{
//Stream Reader Setup
StreamReader answerFile;
answerFile = File.OpenText("C:\\Users\\aabro\\Documents\\_CPT 185\\AshleyBrown_CPT185A01S_Chapter7Lab\\Answer Key.txt");
//Read Answer Key in answerKey Array
while (index < answerKey.Length && !answerFile.EndOfStream)
{
answerKey[index] = char.Parse(answerFile.ReadLine());
index++;
}
//Close answer key file
answerFile.Close();
//clear count
count = 1;
//display answer key in correct answer list box
foreach (char key in answerKey)
{
correctAListBox.Items.Add(count + ". " + key.ToString());
count++;
}
}
private void CompareAnswers()
{
//reset count
count = 1;
for (index = 0; index < answerKey.Length; index++)
{
//determine if answer is right
if (studentAnswers[index] != answerKey[index])
{
wrongAListBox.Items.Add(count + ". " + answerKey[index]);
wrong++;
count++;
}
}
//fail display
if (wrong > 5)
{
MessageBox.Show("Student has failed");
}
//calculations
double pointPerQ = 5;
double wrongTotal = wrong;
double wrongPointTotal = wrong * pointPerQ;
double grade = 100 - wrongPointTotal;
//output grade information
incorrectBox.Text = wrong.ToString();
correctBox.Text = right.ToString();
percentBox.Text = grade.ToString("p0");
}
}
}
this is the current output from running the program, I did double check the file names and contents as well.
output of current code
One issue that I saw in code is using of index in multiple while loops without previously assigning to 0.
I suggest using of local variables(variable which exists only in the current block of code).
Also in my opinion it will be good to declare and initialize new variable in for-loop like this:
for(int index = 0; index < answerKey.Length; index++)
{
// your code
}
it will be more readable and easier if you want later to separate loops in methods or move in service or helper.
private void Form1_Load(object sender, EventArgs e){
for (int i = 0; i < listBox1.Items.Count; i++)
{
lst.Add(listBox1.Items[i].ToString());
}
foreach (var item in lst)
{
lst1.Add(item[2].ToString());
}
}
private void button1_Click(object sender, EventArgs e) {
if (lst1.Contains(textBox1.Text))
{
// *Need to find that particular item from listbox and clear rest of them*\\
}
}
my input is
1-2-3-4-5
6-7-8-9-10
1-9-4-2-3
7-8-1-4-9
so when textbox has value 7
then my listbox must show 6-7-8-9-10 as output and clear rest all items in listbox
Using what you have posted, I do not understanding what exactly you are trying to achieve. Using the two (2) List’s lst and lst1 looks very odd. Without having more information as to what your ultimate goal is I question why you would do this the way you are.
The code below removes the items in the ListBox where the second character does not match the character in the text box. Hope this helps.
private void button1_Click(object sender, EventArgs e) {
if (lst1.Contains(textBox1.Text)) {
int index = lst1.IndexOf(textBox1.Text);
string temp = listBox1.Items[index].ToString();
MessageBox.Show("Character: " + textBox1.Text + " Found at index: " + index + " the string is: " + temp);
listBox1.Items.Clear();
listBox1.Items.Add(temp);
// *Need to find that particular item from listbox and clear rest of them*\\
} else {
MessageBox.Show("Not Found");
}
}
I have been given a coding assignment by my recruiter for a job as a junior developer. There were three choices and I went with a problem that requires calculating a purchase. All items are supposed be taxed 10% unless they are books, food or medicine. Anything imported is taxed an extra 5%, even if they are tax exempt. So I created a form that allows a user to type in the name of the item, two check boxes for whether they are imported or tax exempt, a textbox for inputing price, and a text box for each input. Underneath is a textbox that is supposed to calculate the total sales tax, underneath that is a textbox for the total. The first checkbox is named "Item1Import" the next one is called "Item1Exempt." The price text box is named "Item1Price" and the other "Item1Output." And for each item the number would change, Item2Import, Item3Import, etc. The last two textboxes are called "SalesTax" and "Total."
Here is the code I have so far.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Item1Price_TextChanged(object sender, EventArgs e)
{
if(Item1Exempt.Checked && Item1Import.Checked)
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text)) + (Convert.ToInt32(Item1Price.Text) * 0.05).ToString("C2"));
}
else if(Item1Exempt.Checked && !Item1Import.Checked)
{
Item1Output.Text = (Convert.ToInt32(Item1Price.Text)).ToString("C2");
}
else if(!Item1Exempt.Checked && Item1Import.Checked)
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text) + (Convert.ToInt32(Item1Price.Text) * 0.1) + (Convert.ToInt32(Item1Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item1Output.Text = ((Convert.ToInt32(Item1Price.Text)) + (Convert.ToInt32(Item1Price.Text) * 0.1)).ToString("C2");
}
}
private void Item2Price_TextChanged(object sender, EventArgs e)
{
if (Item2Exempt.Checked && Item2Import.Checked)
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text)) + (Convert.ToInt32(Item2Price.Text) * 0.05).ToString("C2"));
}
else if (Item2Exempt.Checked && !Item2Import.Checked)
{
Item2Output.Text = (Convert.ToInt32(Item2Price.Text)).ToString("C2");
}
else if (!Item2Exempt.Checked && Item2Import.Checked)
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text) + (Convert.ToInt32(Item2Price.Text) * 0.1) + (Convert.ToInt32(Item2Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item2Output.Text = ((Convert.ToInt32(Item2Price.Text)) + (Convert.ToInt32(Item2Price.Text) * 0.1)).ToString("C2");
}
}
private void Item3Price_TextChanged(object sender, EventArgs e)
{
if (Item3Exempt.Checked && Item3Import.Checked)
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text)) + (Convert.ToInt32(Item3Price.Text) * 0.05).ToString("C2"));
}
else if (Item3Exempt.Checked && !Item3Import.Checked)
{
Item3Output.Text = (Convert.ToInt32(Item3Price.Text)).ToString("C2");
}
else if (!Item3Exempt.Checked && Item3Import.Checked)
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text) + (Convert.ToInt32(Item3Price.Text) * 0.1) + (Convert.ToInt32(Item3Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item3Output.Text = ((Convert.ToInt32(Item3Price.Text)) + (Convert.ToInt32(Item3Price.Text) * 0.1)).ToString("C2");
}
}
private void Item4Price_TextChanged(object sender, EventArgs e)
{
if (Item4Exempt.Checked && Item4Import.Checked)
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text)) + (Convert.ToInt32(Item4Price.Text) * 0.05).ToString("C2"));
}
else if (Item4Exempt.Checked && !Item4Import.Checked)
{
Item4Output.Text = (Convert.ToInt32(Item4Price.Text)).ToString("C2");
}
else if (!Item4Exempt.Checked && Item4Import.Checked)
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text) + (Convert.ToInt32(Item4Price.Text) * 0.1) + (Convert.ToInt32(Item4Price.Text) * 0.05)).ToString("C2"));
}
else
{
Item4Output.Text = ((Convert.ToInt32(Item4Price.Text)) + (Convert.ToInt32(Item4Price.Text) * 0.1)).ToString("C2");
}
}
private void SalesTax_TextChanged(object sender, EventArgs e)
{
SalesTax.Text = (((Convert.ToInt32(Item1Output.Text) - Convert.ToInt32(Item1Price.Text)) + ((Convert.ToInt32(Item2Output.Text) - Convert.ToInt32(Item2Price.Text)) + ((Convert.ToInt32(Item3Output.Text) - Convert.ToInt32(Item3Price.Text)) + ((Convert.ToInt32(Item4Output.Text) - Convert.ToInt32(Item4Price.Text)).ToString("C2"));
}
private void Total_TextChanged(object sender, EventArgs e)
{
Total.Text = ((Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)) + (Convert.ToInt32(Item1Output)).ToString("C2"));
}
}
}
The first problem I'm having is whenever I do type into Item1Price, it outputs to Item1Output but it doesn't work with the others, and the "salestax" and "total" textboxes don't show anything either.
The second problem is I can't type a number like "O.OO" but I can do "00" and whenever I delete the number, it crashes.
Any help would be really appreciated. Thank you in advance.
First thing its not in good fashion to post coding assignment in a forum to get help with for a job. If you cant complete the coding assignment by yourself I would suggest you reevaluate your skills and ask yourself if your ready for the position that you're trying to obtain. With that said I remember the days in my beginning when I was going after those positions I probably had no business being in at the time so I can sympathize with that. Now to your code.
First of all, you need to surround your conversions in a try catch block, the reason your application is crashing is because 0.00 will not convert into a integer since there is a decimal there. 00 will work but when you delete them your textbox.text value is now nothing which is not going to convert either and your program will crash. So you will need to add logic to handle an empty string value and not do a conversion. I would suggest you use decimal datatype when dealing with money values. As suggested also I would create a method in which you could pass the check box values and return a string value back to set your textbox values. This could clean up your event handler code cause it seems your calculations are the same.
It's my first post.
I'm trying to make multiple sums in a checkedlistbox in Visual C#. There are 108 numbers, one in each row, and I'm trying to sum the checked item(s) with each one of the rest and print it in a textbox.
I have done this, but I think it's incorrect.
This actually does the sum, but also with the number itself and the whole thing 108 times
I want to add the checked number with the rest numbers in the checkbox.
private void button2_Click(object sender, EventArgs e)
{
foreach(string checkednumber in checkedlistbox1.CheckedItems)
{
double x = Convert.ToDouble(checkednumber);
double a = 0;
for (double y = 0; y < checkedlistbox1.Items.Count; ++y)
{
foreach (string othernumbers in checkedlistbox1.Items)
{
double z = Convert.ToDouble(othernumbers);
sum = x + z;
string str = Convert.ToString(sum);
listbox1.Items.Add(str);
}
}
}
}
Thanks for any help.
You just want to sum the numbers for items that are checked?
double sum = 0;
foreach(object checkedItem in checkedlistbox1.CheckedItems)
{
try
{
sum += Convert.ToDouble(checkedItem.ToString());
}
catch (FormatException e) {} //catch exception where checkedItem is not a number
listbox1.Items.Add(sum.ToString());
}
Your question is incredibly unclear, I'm not really sure if this is what you want at all.
Also you can use linq to achieve it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var result = from num in this.checkedListBox1.CheckedItems.OfType<string>()
select Convert.ToInt32(num);
this.textBox1.Text = result.Sum().ToString();
}
}
}
I want to free type in combobox. When I stop typing I have a delayed task that populates combobox items with some input dependent results. The problem is that my input is overridden by the first item in the list. Is there a way to keep my input?
My sample code is going like this:
public void PopulateCombo(JObject result)
{
Debug.WriteLine("Thread id: " + Thread.CurrentThread.ManagedThreadId);
cbSearch.Items.Clear();
if (result.Value<bool>("success") == true)
{
JArray arr = result.Value<JArray>("data");
for (int i = 0; i < arr.Count; i++)
{
JToken item = arr[i];
cbSearch.Items.Add(new ComboBoxItem( item.Value<string>("name"), item.Value<string>("_id")));
}
cbSearch.DroppedDown = true;
}
}
Edited on 23.06
I'm giving an example of what I'm really trying to do.
Combobox is empty (no items)
User starts typing for example "ja". Combobox sends query to my backend. Should n't be a problem as the call is asynchronous with 1 second delay after user last input.
My backend returns some results (Anton Jamison, James Aaron, James Hetfield, etc., limited to 50)
I want to populate the dropdown list with results, to open it, but as a combobox text i want to keep "ja", so the user can clarify his search further.
User extends his search "ja h". Backend responds with James Hetfield. Result now is only one item and I can set the combobox text now or keep the behavior from above. Not sure which would be better yet.
All this is implemented but at step 4 when I populate the combobox using the function above, the text of the combo is changed from "ja" to the first match of the list. (Anton Jamison in the example). I'm almost sure that there was a simple option for implementing this behavior but I'm not sure if it was in C#.
On comments :
It was a good try but unsuccessful. Once I populate the combobox items my search string is changed to the first match of the list.
I think I don't try to implement the autocomplete feature.
Good catch about the DroppedDown. I move it in the edited version.
I do not have the problem you talked about. The text in the edit box stays the same all the time.
I am using VS2008 though with a standard ComboBox renamed to cbSearch and its event captured (as well as the form's show event).
Rest works nicely.
Seemed like a nice task so I did it.
I also recover the selection, though you can see some flickering.
Most difficult was the synchronization - so I found an easy not tooo ugly solution.
Still, I don't do anything different from you.. maybe you start with a blank ComobBox again, maybe you changed some of the default parameters.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void cbSearch_TextUpdate(object sender, EventArgs e)
{
lastUpdate = DateTime.Now;
allowUpdate = true;
}
DateTime lastUpdate = DateTime.Now;
volatile bool allowUpdate = false;
private void BoxUpdate()
{
while (true)
{
Thread.Sleep(250);
if (allowUpdate)
{
var diff = DateTime.Now - lastUpdate;
if (diff.TotalMilliseconds > 1500)
{
allowUpdate = false;
this.InvokeEx(x =>
{
if (x.cbSearch.Text.Length > 0)
{
x.PopulateCombo(cbSearch.Text);
}
});
}
}
}
}
public void PopulateCombo(string text)
{
int sStart = cbSearch.SelectionStart;
int sLen = cbSearch.SelectionLength;
List<string> cbItems = new List<string>();
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
cbItems.Add(i + text + j);
cbSearch.Items.Clear();
{
for (int i = 0; i < cbItems.Count; i++)
{
cbSearch.Items.Add(cbItems[i]);
}
cbSearch.DroppedDown = true;
}
cbSearch.SelectionStart = sStart;
cbSearch.SelectionLength = sLen;
}
private void Form1_Shown(object sender, EventArgs e)
{
ThreadPool.QueueUserWorkItem(x =>
{
BoxUpdate();
});
}
}
public static class ISynchronizeInvokeExtensions
{
public static void InvokeEx<T>(this T #this, Action<T> action)
where T : System.ComponentModel.ISynchronizeInvoke
{
if (#this.InvokeRequired)
{
#this.Invoke(action, new object[] { #this });
}
else
{
action(#this);
}
}
}
}
Managed to do the same task with the hint of comment 1 + some tweaks. Here is my final code that does the work:
private void cbSearch_TextUpdate(object sender, EventArgs e)
{
timer1.Stop();
timer1.Dispose();
timer1 = null;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
}
delegate void MethodDelegate(JObject result);
void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
Debug.WriteLine(this.cbSearch.Text);
Debug.WriteLine("Thread id: " + Thread.CurrentThread.ManagedThreadId);
Dictionary<string, object> parameters = new Dictionary<string, object>();
parameters["query"] = this.cbSearch.Text ?? "";
this.session.rpc["advanced_search"].execAsync(parameters, results =>
{
this.BeginInvoke(new MethodDelegate(PopulateCombo), new object[] {results.GetResult()});
});
}
public void PopulateCombo(JObject result)
{
Debug.WriteLine("Thread id: " + Thread.CurrentThread.ManagedThreadId);
this.selectedPatientId = "";
string text = cbSearch.Text;
cbSearch.DroppedDown = false;
cbSearch.Items.Clear();
if (result.Value<bool>("success") == true)
{
JArray arr = result.Value<JArray>("data");
for (int i = 0; i < arr.Count; i++)
{
JToken item = arr[i];
cbSearch.Items.Add(new ComboBoxItem( item.Value<string>("name"), item.Value<string>("_id")));
}
try
{
this.cbSearch.TextUpdate -= new System.EventHandler(this.cbSearch_TextUpdate);
cbSearch.DroppedDown = true;
cbSearch.Text = text;
cbSearch.Select(cbSearch.Text.Length, 0);
}
finally {
this.cbSearch.TextUpdate += new System.EventHandler(this.cbSearch_TextUpdate);
}
}
}