Converting listview subitems to double - c#

I am creating a process scheduling calculator on C# and I created to listviews 1 for the inputs and one for the scheduling itself , however when I started coding the FCFS scheduling part I fail to convert the burst time subitem to double so I can add the waiting time here is some parts of the code and a screenshot to the form
public void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
{
MessageBox.Show("Insert the required in the boxes");
}
else
{
ListViewItem Process = new ListViewItem(textBox1.Text);
Process.SubItems.Add(textBox2.Text);
Process.SubItems.Add(textBox3.Text);
Process.SubItems.Add(textBox4.Text);
listView1.Items.Add(Process);
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
textBox4.Text = "";
}
}
private void button2_Click(object sender, EventArgs e)
{
double temp = 0;
//First Come First Served
if (comboBox1.Text == "FCFS")
{
for (int i = 0; i < listView1.Items.Count; i++)
{
ListViewItem WaitingTime = new ListViewItem(listView1.Items[i].Text);
//temp = Convert.ToDouble(listView2.Items[i].SubItems[0]) + Convert.ToDouble(listView2.Items[i + 1].SubItems[0]);
if (listView2.Items.Contains(WaitingTime))
{
WaitingTime.SubItems.Add(temp.ToString());
listView2.Items.Add(WaitingTime);
}
else
{
WaitingTime.SubItems.Add(temp.ToString());
listView2.Items.Add(WaitingTime);
}
}
}
//SJF Non-preemptive
if (comboBox1.Text == "SJF non-preemptive")
{
for (int i = 0; i < listView1.Items.Count; i++)
{
listView2.Items.Add(listView1.Items[i].Text);
}
}
}
I tried several times and searched couple forms and all I get is FormatExpection.

Subitems[0] will hold the first subelement, which is the same as the Text of the item, also you cannot convert a ListViewItem.Subitem into a text, you need to use the Text property.
So you need to use:
listView2.Items[i].SubItems[1].Text
In your convert, also I recommend to use Double.TryParse instead of Convert.ToDouble, is faster and will tell you if it was parsed or not.

Related

How to annotate a changed item in a listbox with a *

I just need help on how to annotate a changed item in the list box if the user changes something using the text boxes provided.
namespace HW1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] values = new string[5];
values[0] = textBox1.Text;
values[1] = textBox2.Text;
values[2] = textBox3.Text;
values[3] = textBox4.Text;
values[4] = textBox5.Text;
string[] temp = new string[5];
temp[0] = textBox1.Text;
temp[1] = textBox2.Text;
temp[2] = textBox3.Text;
temp[3] = textBox4.Text;
temp[4] = textBox5.Text;
if(temp != values)
{
listBox1.SelectedIndex = 0 + "*";
listBox1.Text = values[1] + "*";
listBox1.Text = values[2] + "*";
listBox1.Text = values[3] + "*";
listBox1.Text = values[4] + "*";
}
listBox1.Items.Clear();
for (int i = 0; i < values.Length; i++)
{
listBox1.Items.Add(values[i].ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
The program will simply replace the old input from the text box with the new without displaying a * next to the item that has changed.
Your code doesn't actually compile... not sure how this line would ever work...
listBox1.SelectedIndex = 0 + "*";
Anyway - the main problem is that your for loop adds in values without the star to the list box
for (int i = 0; i < values.Length; i++)
{
listBox1.Items.Add(values[i].ToString()); //values[i] never has a star stored in it!
}
How about something like this...?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] values = new [] { textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, textBox5.Text };
for (int i = 0; i < values.Length; i++)
{
if (listBox1.Items.Count < i + 1)
{
listBox1.Items.Add(values[i].ToString());
continue;
}
string unedited = listBox1.Items[i].ToString();
if (!string.IsNullOrEmpty(unedited) && unedited.Last() == '*')
unedited = listBox1.Items[i].ToString().Substring(0, listBox1.Items[i].ToString().Length - 1);
if (unedited != values[i])
listBox1.Items[i] = values[i] + "*";
else
listBox1.Items[i] = values[i];
}
}
private void button2_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
This compares the list items to the textbox values.
If the textbox value doesn't exist, a listbox item is created.
If the listbox item doesn't match the textbox value, it has a * appended to it.
If an existing value (ignoring the star) is the same as the textbox value, it is updated to ensure the star is removed.

values a re not being displayed in TextBox

in this program, when the Recall button (recallBtn_Click()) is clicked, it calls a method (that calculates directions) from another class which should then call the showPath() method. the show path method should then display its output in a textBox. But the values don't show even though i can see from debugging that the values are being sent to the text box. can anybody tell me where i went wrong?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
storeRetSelect.SelectedIndex = 0;
PrioritySelect.SelectedIndex = 0;
}
public void showPath(List<PathFinderNode> mPath)
{
var T = new Form1().directionsTextBox;
foreach (PathFinderNode node in mPath)
{
if ((node.X - node.PX) > 0) { T.Text += "Right" + System.Environment.NewLine ; }
if ((node.X - node.PX) < 0) { T.Text += "Left" + System.Environment.NewLine; }
if ((node.Y - node.PY) > 0) { T.Text += "UP" + System.Environment.NewLine; }
if ((node.Y - node.PY) < 0) { T.Text += "Down" + System.Environment.NewLine; }
}
}
private void recallBtn_Click(object sender, EventArgs e)
{
var path = new pathPlan();
string desigString = inputTextBox.Text;
int[] desig = new int[3];
for (int i = 0; i < desigString.Length; i++) { desig[i] = (int)char.GetNumericValue(desigString[i]); }
path.Recall(desig[1], desig[2], (-1) * desig[0]);
}
}
With this line you are initialising a new object and get the reference of the textbox there.
var T = new Form1().directionsTextBox;
But I assume you want to use the textbox of the form which is allready open. Change the line to the following to access the textbox of the current object.
var T = this.directionsTextBox;

How can I use text property of dynamic created textfield?

I have this code, which dynamically creates some textfields for me. k is taken from user btw.
for (int i = 0; i < k; i++)
{
TextBox t1 = new TextBox();
t1.Parent = groupBox2;
t1.Left = textBox2.Left;
t1.Top = textBox2.Top + (i + 1) * 40;
t1.Name = "text" + (i + 1);
t1.Enabled = true;
groupBox2.Controls.Add(t1);
}
What i want to do is, after this creating phase is done, when the user presses groupbox2's "OK" button, I want to take the created textfields' text properties, but so far I don't know how could this be done, since I gave textfields a name, I tried this but didn't work.
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
node1.array[i] = Convert.ToInt32("text"+(i+1).Text);
}
}
Any help would be nice, thanks.
Try this method:
private void button3_Click(object sender, EventArgs e)
{
node1.name = textBox2.Text;
for (int i = 0; i < k; i++)
{
TextBox txtBox = (TextBox)groupBox2.FindControl("text" + (i + 1));
if (txtBox != null)
{
node1.array[i] = txtBox.Text;
}
}
}
Loop through your text boxes in groupBox1 and get their names,Try this:
List<string> TextBoxesName=new List<string>();
foreach (Control item in groupBox1.Controls)
{
if (item is TextBox)
{
TextBoxesName.Add((item as TextBox).Text);
}
}
Set to your dynamic texboxes ID and than you can do groupBox2.FindControl("dynamic_texbox_id") to get your text box
Easiest solution is to put your listboxes in a collection of some sort
List<ListBox> listboxes = new List<ListBox>();
for (...)
{
...
listboxes.add(listbox);
}
Then you can refer back to them whenever you want
Or since you're adding them to a groupbox, why not go through that collection?

Numbered list on Richtextbox

I'm trying to add numbered list functionality to a text editor. RichTextbox already provides the SelectionBullet property to change a selection to a bulleted list. But i was unable to find a similar property to generate numbered list. Is there any standard way to create a numbered list on Richtextbox. If not, i would have to implement it myself so code snips that could help me do that will help, Thank you.
I know that a link is not gernerally accepted as a good answer, however the article RichTextBox with Search Line Numbering, Bulleting, Printing, Searching Support on CodeProject could probably help you out quite a bit with what you are looking for.
In this article, the author extends the RichTextBox control into something that can do what you are asking (and more), plus the code is posted there for all to see.
Well, i implemented it as follows.
private void btnNumbers_Click(object sender, EventArgs e)
{
string temptext = rtbMain.SelectedText;
int SelectionStart = rtbMain.SelectionStart;
int SelectionLength = rtbMain.SelectionLength;
rtbMain.SelectionStart = rtbMain.GetFirstCharIndexOfCurrentLine();
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = "1. ";
int j = 2;
for( int i = SelectionStart; i < SelectionStart + SelectionLength; i++)
if (rtbMain.Text[i] == '\n')
{
rtbMain.SelectionStart = i + 1;
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = j.ToString() + ". ";
j++;
SelectionLength += 3;
}
}
private void rtbMain_KeyDown(object sender, KeyEventArgs e)
{//this piece of code automatically increments the bulleted list when user //presses Enter key
int tempNum;
if (e.KeyCode == Keys.Enter)
try
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()]))
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.')
tempNum = int.Parse(rtbMain.Text.Substring(rtbMain.GetFirstCharIndexOfCurrentLine(),2));
else tempNum = int.Parse(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()].ToString());
if (rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1] == '.' || (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.'))
{
tempNum++;
rtbMain.SelectedText = "\r\n" + tempNum.ToString() + ". ";
e.SuppressKeyPress = true;
}
}
}
catch{}
}
Here is my answer... which is easily readable and refineable. I took a much different approach but added the ability to remove the numbered list within the selection if it already exists. Please note that so far I have only lightly tested it and it seems to work good... but it may need further refinement.
private void btnOrdered_Click(object sender, EventArgs e)
{
string[] splitSelection = null;
// If selection split selection else split everything
if (this.txtCaptionEditor.SelectionLength > 0)
{
splitSelection = this.txtCaptionEditor.SelectedText.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
else
{
splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
bool Exists = false;
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
// If Ordered List Allready exists in selection then remove else add
if (!string.IsNullOrEmpty(splitSelection[i]))
{
if (splitSelection[i].Substring(0, 2) == "1.") { Exists = true; }
}
}
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
int lineCount = (i + 1);
if (Exists)
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(Convert.ToString(lineCount) + ". ", "");
}
else
{
if(!string.IsNullOrEmpty(splitSelection[i]))
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(splitSelection[i], Convert.ToString(lineCount) + ". " + splitSelection[i]);
}
}
}
}
private void txtCaptionEditor_KeyDown(object sender, KeyEventArgs e)
{
string[] splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
if (e.KeyCode == Keys.Enter)
{
// Get Current Line Position
int currentLine = this.txtCaptionEditor.GetLineFromCharIndex(this.txtCaptionEditor.SelectionStart);
// Only Run if the previous line is greater than zero
if ((currentLine) >= 0)
{
// Loop through 100 possible numbers for match you can go higher
// If you think your numbered list could go above 100
for (int i = 0; i < 100; i++)
{
if (splitSelection[(currentLine)].Substring(0, 2) == Convert.ToString((i + 1)) + ".")
{
// If the substring of the current line equals a numbered list value.. enumerate next line
this.txtCaptionEditor.SelectedText = "\n" + (i + 2) + ". ";
e.SuppressKeyPress = true;
}
}
}
}
}

Textbox display formatting

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("#,#");

Categories

Resources