listbox selection update textbox - c#

Need to update 3 text boxes with decimals, after selecting an item in a Listbox.
link to files: https://www.dropbox.com/s/xj2efe5sxsolswk/midterm.zip
Format in listbox: "Name |XX| |XX| |XX|" e.g. "Matt |100| |90| |80|"
How do I recall the 3 values associated with a selected index from the listbox, to calculate 3 values and update 3 text boxes, associated with that listbox selection?
I have created 3 lists to attempt to store what I need. I am saving the score inputs to scoreList2, but not sure how to link them when associating it with the ListBox.
public static List<string> scoreList = new List<string>();
public static List<decimal> scoreList2 = new List<decimal>();
public static List<object> scoreList3 = new List<object>();
Code:
private void Form1_Load(object sender, EventArgs e)
{
(all hard coded cuz I'm a noob)
//txtScoreTotal.Text = tempNum1.ToString();
//txtScoreTotal.text =
//txtScoreCount.Text = tempNum2.ToString();
//txtAverage.Text = tempNum3.ToString();
lbStudents.Items.Add(tempInfo1 + " " + tempNum1 + " " + tempNum2 + " " + tempNum3);
}
private void lbStudents_SelectedIndexChanged(object sender, EventArgs e)
{
/*
txtScoreTotal.Text = tempNum1.ToString();
//txtScoreTotal.Text = selected listbox scoretotal
txtScoreCount.Text = tempNum2.ToString();
//txtScoreTotal.Text = selected listbox scorecount
txtAverage.Text = tempNum3.ToString();
//txtSCoreTotal.Text = selected listbox average
*/
txtScoreTotal.Text = lbStudents.SelectedItem.ToString();
}

You can use String.Split method and LINQ like this:
private void lbStudents_SelectedIndexChanged(object sender, EventArgs e)
{
if(lbStudents.SelectedItem != null)
{
decimal result;
var numbers = lbStudents.SelectedItem.ToString()
.Split(new [] { '|' }, StringSplitOptions.RemoveEmptyEntries)
.Where(x => decimal.TryParse(x, out result))
.ToList();
txtBox1.Text = numbers[0];
txtBox2.Text = numbers[1];
txtBox3.Text = numbers[2];
}
}

Related

how to get dynamic created text box value from panel in c# on button click

I Create dynamic text box on button click inside panel and store number
and want to retrieve its text and make total of that number how can i do that?
Following is my code for text box generation
private void btnMaterialAdd_Click(object sender, EventArgs e)
{
TextBox[] txtTeamNames = new TextBox[100];
txtTeamNames[i] = new TextBox();
string name = "TeamNumber" + i.ToString();
txtTeamNames[i].Location = new Point(1, i * 30 );
txtTeamNames[i].Width = 30;
txtTeamNames[i].Name = "ID" + i;
txtTeamNames[i].Visible = true;
int num = i + 1 ;
txtTeamNames[i].Text = num.ToString();
panel1.Controls.Add(txtTeamNames[i]);
}
How to count total value of each text box and display?
Get rid of the Array and use a List at Class Level (not a local variable in your method):
private List<TextBox> TextBoxes = new List<TextBox>();
private void btnMaterialAdd_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
int i = TextBoxes.Count + 1;
tb.Location = new Point(1, i * 30);
tb.Width = 30;
tb.Name = "ID" + i;
tb.Text = i.ToString();
TextBoxes.Add(tb);
panel1.Controls.Add(tb);
}
Now you can iterate over that List when to get a total:
private void btnTotal_Click(object sender, EventArgs e)
{
int value;
int total = 0;
foreach (TextBox tb in TextBoxes)
{
if (int.TryParse(tb.Text, out value))
{
total = total + value;
}
else
{
MessageBox.Show(tb.Name + " = " + tb.Text, "Invalid Value");
}
}
MessageBox.Show("total = " + total.ToString());
}

Need help appending a variable in listbox

When the Add button is pressed the price is taken from the second half of a 'split' line in the first list box. This is then multiplied by a value entered in a textbox or just entered as is into the second listbox.
I have then added a line below it in the second list box with the total price. When a new item is added the code removes the previous total price and replaces it with the new updated total price.
I'm looking to then append (add all the prices being listed in the second listbox) the prices together in the 'total price' section of the last line of the second list box.
Below is the code I have written so far.
private void button1_Click(object sender, EventArgs e)
{
string TheItem = Convert.ToString(listBox1.SelectedItem);
string[] theSplits = TheItem.Split(' ');
string FirstSplit = theSplits[0];
string SecondSplit = theSplits[1];
Decimal theNewTotal;
Decimal theValue;
if (textBox1.Text == "")
{
listBox2.Items.Add(TheItem);
listBox2.Items.Add("Total Price:" + SecondSplit);
}
else
{
theValue = Convert.ToDecimal(SecondSplit) * Convert.ToDecimal(textBox1.Text);
listBox2.Items.Add(textBox1.Text + "x " + TheItem);
theNewTotal = theValue;
listBox2.Items.Add("Total Price:" + theNewTotal);
}
if (listBox2.Items.Count > 2)
{
int theNumber = listBox2.Items.Count;
listBox2.Items.RemoveAt(theNumber-3);
}
}
You'd be better off starting by removing the total price first, as you expend some effort trying to work around that. So something like:
private void button1_Click(object sender, EventArgs e) {
RemoveLastTotal();
AppendPrices();
AppendTotal();
}
private void RemoveLastTotal() {
var lastItemIndex = listBox2.Items.Count-1;
if (listBox2.Items[lastItemIndex].StartsWith("Total Price:"))
{
listBox2.Items.RemoveAt(lastItemIndex);
}
}
private void AppendPrices() {
string TheItem = Convert.ToString(listBox1.SelectedItem);
string[] theSplits = TheItem.Split(' ');
string itemDesc = theSplits[0];
string itemPrice = theSplits[1];
float quantity = (string.IsNullOrEmpty(textBox1.Text))? 0: float.Parse(textBox1.Text)
if (quantity==0) {
listBox2.Items.Add(TheItem);
} else {
var lineTotal = Convert.ToDecimal(itemPrice) * quantity;
listBox2.Items.Add(textBox1.Text + " x " + TheItem + " = " + lineTotal);
}
}
private void AppendTotal()
{
var total = 0;
foreach(var item in listBox2.Items)
{
var splits = item.Split(' ');
total += decimal.parse(splits[splits.length-1]);
}
listBox2.Items.Add("Total Price:" + total);
}
That said, if you really want to do it "properly", you should separate the view i.e. the listbox from the model (DataTable for instance).

I am trying to display the number of occarances of a letter, but the output only shows the last letter

I am trying to print a list of occurrences of each letter in thee text inputed by the user but the textbox only shows the last letter.
private void button1_Click(object sender, EventArgs e)
{
//disable the text box so text cannot be entered until reset is pressed
textBox3.Enabled = false;
//make a list containing the alphabets
List<string> Alphabets = new List<string>();
Alphabets.Add("A");
Alphabets.Add("B");
Alphabets.Add("C");
Alphabets.Add("D");
Alphabets.Add("E");
Alphabets.Add("F");
Alphabets.Add("G");
Alphabets.Add("H");
Alphabets.Add("I");
Alphabets.Add("J");
Alphabets.Add("K");
Alphabets.Add("L");
Alphabets.Add("M");
Alphabets.Add("N");
Alphabets.Add("O");
Alphabets.Add("P");
Alphabets.Add("Q");
Alphabets.Add("R");
Alphabets.Add("S");
Alphabets.Add("T");
Alphabets.Add("W");
Alphabets.Add("X");
Alphabets.Add("Y");
Alphabets.Add("Z");
//make a while loop to cycle through alphabets loop
int i = 0;
while (i < Alphabets.Count)
{
//assign value in the list Alphabets
string SearchFor = Alphabets[i];
//access textbox and make it to upper small small and captital are the same
string SearchIn = textBox3.Text.ToUpper();
//list to count the number of instances used for each letter
List<int> FoundCount = Search(SearchFor, SearchIn);
//if statement so only letters that occor more than 0 times are displayed
if (FoundCount.Count > 0)
{
//string to display the number of occorances
//convert to toString so it can be displayed in the TextBox
string Counts = Alphabets[i] + ": " + FoundCount.Count.ToString();
//create a message box to display the output
//MessageBox.Show(Counts);
textBox4.Text = String.Join(Environment.NewLine, Counts);
}
//adds 1 each time as long as i <alphabet.count
i++;
}
}
//List takes 2 arguements (SearchFor, SearchIn) Results can be passed to FoundCounts and number of occrances can be calculted
List<int> Search(string Target, string Subject)
{
//List to count the number of occarances for each letter
List<int> Results = new List<int>();
//for loop for comparison (counting occarances) to compare each letter in textbox to each letter in alphabets
for (int Index = 0; Index < (Subject.Length - Target.Length) + 1; Index++)
{
//if to calculate the number of times a letter is used.
if (Subject.Substring(Index, Target.Length) == Target)
{
//adds the number in index to the list Result
Results.Add(Index);
}
}
return Results;
}
i made multiline as true but that didnt work
I'm pretty sure the issue with your code is here:
textBox4.Text = String.Join(Environment.NewLine, Counts);
You're overwriting the text every time, instead you should do:
textBox4.Text += String.Join(Environment.NewLine, Counts);
This isn't a direct answer to the question, but this might be valuable for the OP.
This code does everything that the original code did (and also fixes the issue raised in the question):
private void button1_Click(object sender, EventArgs e)
{
var SearchIn = textBox3.Text.ToUpper();
var query =
from c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let count = SearchIn.Count(x => x == c)
select String.Format("{0}: {1}", c, count);
textBox4.Text = String.Join(Environment.NewLine, query);
}
There you go, a version that uses lists. :-)
private void button1_Click(object sender, EventArgs e)
{
var SearchIn = textBox3.Text.ToUpper();
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToList();
var query =
from c in alphabet
let matches = SearchIn.Where((x, n) => x == c).ToList()
select String.Format("{0}: {1}", c, matches.Count());
textBox4.Text = String.Join(Environment.NewLine, query);
}

Adding all values selected from the Listbox

So this is how far I have gotten I am not really sure.
So I populated my listbox1 with values such as 1.2, 1.3
So how do I add all the selected values of my listbox and caculate the average?
If you could help me I be very thankful.
List<double> doubleList = new List<double>();
private void btnGetAverage_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
}
}
First make the SelectionMode property of your listbox as MultiSimple. Then try this code.
double total = 0;
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
{
total += Double.Parse(listBox1.SelectedItems[i].ToString());
}
MessageBox.Show("The average is: " + total / listBox1.SelectedItems.Count);
You can you the Average method:
List<double> doubleList = new List<double>();
private void btnGetAverage_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
var myList = listbox1.SelectedItems as List<double>;
return myList.Average();
}
}
Add your list of doubles to your ListBox like this:
listBox1.DataSource = doubleList;
Then this will get you the average of only selected items:
var average = listBox1.SelectedItems.Cast<double>().Average();

c# windows form application dynamic objects value

i have made a mistake of re-inventing the wheel. There are options
but somehow i like the feel of this.
Sorry but don't have enough rep to post an image.
This is how the form looks like:
SNO.-------ITEMS--------FROM--------TO---------QUANTITY // labels
[ 1 ]-------[-----------▼]---[--------]----[--------]------[-------------] {NEW} {DELETE} //textboxes and buttons
I've got the 'new' button click event to generate a row, and serial number to be automatic
and inserted the items into the collections from Properties panel.
Delete button deletes an entire row and shifts both the button up on Y position.
I need to assign the value of quantity [(TO - FROM ) + 1] in the QUANTITY text boxes,
for which i have the code as :
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
calculate_quant(this, e);
quanty = result;
}
public static string result;
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
TextBox quan;
quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
result = quantity.ToString();
quan.Text = result;
}
return result;
}
count is initialized at 1 on form load, keeps increasing with number of rows
the same code works in the delete row method
public void delete_row(object sender, EventArgs e) //function to delete a row
{
TextBox snum;
snum = (TextBox)this.Controls.Find("SNO"+count, true)[0];
snum.Dispose();
...//delete other row elements
}
please help me figure out why it doesnt work for the print_quant / calculate_quant methods
I made some changes to your code. I changed the return on your calculate method to a string, and added a quanty.Text=calculatemethod line to your print method
public void print_quant(object Sender, EventArgs e)
{
TextBox quanty;
quanty = (TextBox)this.Controls.Find("QUANTITY" + (count), true)[0];
//add this line
quanty.Text = calculate_quant(this, e).ToString();
}
public static string result;
//change this
//public void calculate_quant(object sender, EventArgs e)
//to
public string calculate_quant(object sender, EventArgs e)
{
TextBox sfrom;
sfrom = (TextBox)this.Controls.Find("SFRM" + count, true)[0];
TextBox sto;
sto = (TextBox)this.Controls.Find("STO" + count, true)[0];
//this isn't being used here
//TextBox quan;
//quan = (TextBox)this.Controls.Find("QUANTITY" + count, true)[0];
//if (!string.IsNullOrEmpty(sfrom.Text) && !string.IsNullOrEmpty(sto.Text))
{
int to = Convert.ToInt32(sto.Text);
int from = Convert.ToInt32(sfrom.Text);
int quantity = (to - from) + 1;
return quantity.ToString();
}
}
Edit
try this.
Create a usercontrol and make it look exactly like one of your rows.
add a property variable for each of the boxes
//whenever you Sno="something" the textbox will automatically be updated.
private string _Sno="00000";
public string Sno{get{return _Sno;}set{_sno=value; SnoTextBox.Text=value;}}
do this for each of your textboxes.
on your main form now you can add a flowpanel, they a bit tricky at first. when you add your new Usercontrol to it, they will automatically be added from the top down, or up, or however you set it up.
When you want to add a new row, just add your new Usercontrol to the flowpanel
FlowPanel flowPanel =new FlowPanel();
FlowPanel.Controls.Add(new myUserControl());
to delete
FlowPanel.Controls.RemoveAt(2);
This is really poorly written, but I am out of time. Either ignore me altogether, or try to figure it out. Sorry I couldn't be more help.
this worked for me
private void textBox_TextChanged(object sender, EventArgs e)
{
TextBox quant;
int x = count - 1;
string num = Convert.ToString(x);
quant = (TextBox)this.Controls.Find("QUANTITY" + x , true)[0];
TextBox to = (TextBox)this.Controls.Find("STO" + x, true)[0];
TextBox from = (TextBox)this.Controls.Find("SFRM" + x, true)[0];
string tovalue = to.Text;
int to1 = Convert.ToInt32(tovalue);
string fromvalue = from.Text;
int from1 = Convert.ToInt32(fromvalue);
int result = (to1 - from1) + 1 ;
if (result > 0)
{
string result1 = Convert.ToString(result);
quant.Text = result1;
}
}
after adding
STO.TextChanged += new System.EventHandler(textBox_TextChanged);
at the function that was generating the boxes where i needed to calculate :)

Categories

Resources