Calculate value automatically when selecting a decimal in combobox - c#

Im trying to get the selected value of my 4 comboboxes and add them together automatically in a windows form.
The comboboxes items are decimals, 0,75 , 0,8 etc.
How do i add all the values selected from the comboboxes together into a textbox?
I have tried for 5 hours now and really cant figure it out.
FYI im really a beginner.
Thanks!

You can handle TextChanged event on all combo boxes, calculate the sum and assign the result to the text box.
private void Form1_Load(object sender, EventArgs e)
{
foreach (var comboBox in this.Controls.OfType<ComboBox>())
{
comboBox.TextChanged += ComboBox_TextChanged;
InitializeComboBox(comboBox);
}
}
private void ComboBox_TextChanged(object sender, EventArgs e)
{
double result = 0;
foreach (var comboBox in this.Controls.OfType<ComboBox>())
{
if (!string.IsNullOrEmpty(comboBox.Text))
{
result += Convert.ToDouble(comboBox.Text);
}
}
textBox1.Text = result.ToString();
}
private void InitializeComboBox(ComboBox comboBox)
{
for (int index = 0; index < 10; index++)
{
comboBox.Items.Add(index + 0.5);
}
}

Related

How to replace previous item of listbox with next item using backgroundworker c#?

I am adding items to the listbox using backgroundworker. It is showing all the items present in the list one by one after some interval of time. I want to show only current item in the list and not all the items.
This is what I have tried.
private void backgroundWorker3_DoWork(object sender, DoWorkEventArgs e)
{
List<string> result = new List<string>();
var found = obj.getFiles();//List<strings>
if (found.Count != 0)
{
for (int i = 0; i < found.Count; i++)
{
int progress = (int)(((float)(i + 1) / found.Count) * 100);
if (found[i].Contains("SFTP"))
{
result.Add(found[i]);
(sender as BackgroundWorker).ReportProgress(progress, found[i]);
}
System.Threading.Thread.Sleep(500);
}
e.Result = result;
}
}
private void backgroundWorker3_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
listBox3.Items.Add(e.UserState);
}
I want to show only current item in the list and not all the items.
Although this is a bit of a hack, I think it should work for what you describe:
// just call clear first
listBox3.Items.Clear();
listBox3.Items.Add(e.UserState);
Truth be told, are you sure you want a ListBox in this circumstance? After all, it's not really a list, it's only an item.

How to get sum of selected DataGrid values in a C# WPF app?

I have a C# WPF app, and my goal is to get the sum of selected row values from a DataGrid, and set a textbox with this total. This sum calculation is triggered by an event that detects when the selected items have changed.
The problem is that when I select many rows at once or select all with Ctrl + A, I get unpredictable sum values.
To troubleshoot, I bound the datagrid with 100 rows, each with an amount of 1. I then selected all items with Ctrl + A. The total sum should be 100, but it caps at 7 or 8 units.
Below is what I have so far. Anyone see the problem?
private void DgDailyTransactions_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
decimal sum = 0;
for (int i = 0; i < dgDailyTransactions.SelectedItems.Count; i++)
{
TextBlock tb = dgDailyTransactions.Columns[1].GetCellContent(dgDailyTransactions.SelectedItems[i]) as TextBlock;
if (tb != null)
{
sum += Convert.ToDecimal(tb.Text);
}
}
tbxSelectedDailyTransactionsTotal.Text = sum.ToString();
}
Suppose your class looks like this:
public class Sales
{
public int Order { get; set; }
public decimal Amount { get; set; }
}
Make a simple method as under:
private void FindAmount()
{
decimal totalSum = 0;
//Add amounts of selected
if (MyDTGRID.SelectedItems.Count > 0)
{
for (int i = 0; i <= dgDailyTransactions.SelectedItems.Count - 1; i++)
{
Sales sales = dgDailyTransactions.SelectedItems[i] as Sales;
decimal amount = sales.Amount;
totalSum += amount;
}
}
myTextBlock.Text = totalSum.ToString();
}
Simply call the method in your selectedCellsChanged Event
private void DgDailyTransactions_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
{
FindAmount();
}
I hope this helps.
for the sum method you can do it using linq (if you don't know I strongly advise you to learn linq, very strong tool in C#), also would advise you to use MVVM, will make your code much easier to debug in future :
private void dgDailyTransactions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
List<Sales> myList=dgDailyTransactions.SelectedItems.Cast<Sales>();
decimal totalSum = 0;
if (myList.Count() > 0)
{
totalSum = myList.Sum(item => item.Amount);
}
myTextBlock.Text = totalSum.ToString();
}
in MVVM (if you use it) you would need just that line in Model :
private void dgDailyTransactions_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
contexte.SelectedSales= new ObservableCollection<Sales>(dgDailyTransactions.SelectedItems.Cast<Affaire>());
}
then you use formula in your ViewModel in set section of SelectedSales

Get Count of Items in WPF Toolkit AutoCompleteBox Dropdown

Is there a way to get the count of the items currently showing in the dropdown in a WPF toolkit autocompletebox?
Or you could even just do this and avoid the loop:
private void AutoCompleteBox_Populated(object sender, PopulatedEventArgs e)
{
int count = ((ReadOnlyCollection<object>)e.Data).Count;
}
Handle the Populated event:
private void AutoCompleteBox_Populated(object sender, PopulatedEventArgs e)
{
int count = 0;
foreach (var item in e.Data)
count++;
string text = count + " items shown!";
}

Identify the Listbox Item through specific item

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");
}
}

C# form - Checkboxes

I'm wondering how to restrict my checkbox from adding to my listbox. At the moment when the user checks the checkbox it will add "Anchovies" to the listbox. What I don't want to happen is when the user deselects the checkbox and re selects it again, "Anchovies" is added to the listbox again (showing two lots of "Anchovies").
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
listBox1.Items.Add("Anchovies");
double total = Convert.ToDouble(textBox2.Text);
total = total + .5;
textBox2.Text = Convert.ToString(total);
}
}
The key is to check if Anchovies already exists on the listBox1 items.
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
//If the item is already there, we don't do anything.
if (!listBox1.Items.Contains("Anchovies")) {
listBox1.Items.Add("Anchovies");
double total = Convert.ToDouble(textBox2.Text);
total = total + .5;
textBox2.Text = Convert.ToString(total);
}
}
}
Do it this way
if (checkBox1.Checked)
{
if(!listBox1.Items.Contains("Anchovies"))
listBox1.Items.Add("Anchovies");
double total = Convert.ToDouble(textBox2.Text);
total = total + .5;
textBox2.Text = Convert.ToString(total);
}
To fix this issue, you need to check your list box(for this value, either it is already there or not) before inserting any value in it.
e.g
foreach (var item in listBox1.Items )
{
if(item.ToString() != "Anchovies")
{
listBox1.Items.Add("Anchovies");
}
// other code here.
}

Categories

Resources