C# sort values from textboxes from min to max - c#

I want to take the values from my textboxes when I press the FIFO button, detect the smallest one and do the operations starting with the smallest number in ti and t until the biggest one, then store all that in tf.
This is what my program looks like:
Here's my code:
private void fifo_Click(object sender, EventArgs e)
{
int c = 0;
//Hace tf
tfA.Text = (Convert.ToInt32(ta.Text) + Convert.ToInt32(tiA.Text)).ToString();
c = Convert.ToInt32(tfA.Text);
tfB.Text = (Convert.ToInt32(tb.Text) + c).ToString();
c = Convert.ToInt32(tfB.Text);
tfC.Text = (Convert.ToInt32(tc.Text) + c).ToString();
c = Convert.ToInt32(tfC.Text);
tfD.Text = (Convert.ToInt32(td.Text) + c).ToString();
c = Convert.ToInt32(tfD.Text);
tfE.Text = (Convert.ToInt32(te.Text) + c).ToString();
c = Convert.ToInt32(tfE.Text);
tfF.Text = (Convert.ToInt32(tf.Text) + c).ToString();
// Hace T
T1.Text = (Convert.ToInt32(tfA.Text) - Convert.ToInt32(tiA.Text)).ToString();
T2.Text = (Convert.ToInt32(tfB.Text) - Convert.ToInt32(tiB.Text)).ToString();
T3.Text = (Convert.ToInt32(tfC.Text) - Convert.ToInt32(tiC.Text)).ToString();
T4.Text = (Convert.ToInt32(tfD.Text) - Convert.ToInt32(tiD.Text)).ToString();
T5.Text = (Convert.ToInt32(tfE.Text) - Convert.ToInt32(tiE.Text)).ToString();
T6.Text = (Convert.ToInt32(tfF.Text) - Convert.ToInt32(tiF.Text)).ToString();
// Hace E
E1.Text = (Convert.ToInt32(T1.Text) - Convert.ToInt32(ta.Text)).ToString();
E2.Text = (Convert.ToInt32(T2.Text) - Convert.ToInt32(tb.Text)).ToString();
E3.Text = (Convert.ToInt32(T3.Text) - Convert.ToInt32(tc.Text)).ToString();
E4.Text = (Convert.ToInt32(T4.Text) - Convert.ToInt32(td.Text)).ToString();
E5.Text = (Convert.ToInt32(T5.Text) - Convert.ToInt32(te.Text)).ToString();
E6.Text = (Convert.ToInt32(T6.Text) - Convert.ToInt32(tf.Text)).ToString();
//Hace I
I1.Text = (Convert.ToDecimal(ta.Text) / Convert.ToDecimal(T1.Text)).ToString();
I2.Text = (Convert.ToDecimal(tb.Text) / Convert.ToDecimal(T2.Text)).ToString();
I3.Text = (Convert.ToDecimal(tc.Text) / Convert.ToDecimal(T3.Text)).ToString();
I4.Text = (Convert.ToDecimal(td.Text) / Convert.ToDecimal(T4.Text)).ToString();
I5.Text = (Convert.ToDecimal(te.Text) / Convert.ToDecimal(T5.Text)).ToString();
I6.Text = (Convert.ToDecimal(tf.Text) / Convert.ToDecimal(T6.Text)).ToString();
//X1 2 y 3
X1.Text = ((Convert.ToDecimal(T1.Text) + Convert.ToDecimal(T2.Text) + Convert.ToDecimal(T3.Text) + Convert.ToDecimal(T4.Text) + Convert.ToDecimal(T5.Text) + Convert.ToDecimal(T6.Text)) / 6).ToString();
X2.Text = ((Convert.ToDecimal(E1.Text) + Convert.ToDecimal(E2.Text) + Convert.ToDecimal(E3.Text) + Convert.ToDecimal(E4.Text) + Convert.ToDecimal(E5.Text) + Convert.ToDecimal(E6.Text)) / 6).ToString();
X3.Text = ((Convert.ToDecimal(I1.Text) + Convert.ToDecimal(I2.Text) + Convert.ToDecimal(I3.Text) + Convert.ToDecimal(I4.Text) + Convert.ToDecimal(I5.Text) + Convert.ToDecimal(I6.Text)) / 6).ToString();
comp1 = Convert.ToDecimal(X3.Text);
}
EDIT: I managed to do what I wanted. I just put the values in an array and sorted them, then equaled the textbox.Text to each one. Worked pretty well. Thank you for the help.

My suggestion would be:
// list holding the ti value and the three controls: ti, t and tf
var controls = new List<Tuple<int, Control, Control, Control>>();
// add all the controls together with the sorting key, the ti value (just an example, but here you add the tiValue and the ti control, t control and tf control
controls.Add(new Tuple<int, Control, Control, Control>(0, null, null, null));
// sort everything
controls.Sort((t1, t2) => t1.Item1.CompareTo(t2.Item1));
// loop through the controls in the right order and perform the logic
foreach (var t in controls)
{
var tiValue = t.Item1;
var tiControl = t.Item2;
var tControl = t.Item3;
var tfControl = t.Item4;
// Do the things to the controls and their values...
}

Can't access pastebin or imgur where I am but I'll give this a shot. Textboxes are a terrible idea for this though.
public static void SortAndSumTextboxes()
{
Form form = new Form();
var tiControls = form.Controls.OfType<TextBox>().Where(tb => Regex.IsMatch(tb.Name, "^ti.$"));
var tControls = form.Controls.OfType<TextBox>().Where(tb => Regex.IsMatch(tb.Name, "^t.$"));
var tiSorted = tiControls.Select(tb => int.Parse(tb.Text)).OrderBy(i => i);
var tSorted = tControls.Select(tb => int.Parse(tb.Text)).OrderBy(i => i);
int c = 1; // some constant
var tfValues = tiSorted.Zip(tSorted, (a, b) => a + b + c).ToArray();
var tfControls = form.Controls.OfType<TextBox>().Where(tb => tb.Name.StartsWith("tf")).OrderBy(tb => tb.Name).ToArray(); ;
for (int i = 0; i < tfControls.Length; i++)
{
tfControls[i].Text = tfValues[i].ToString();
}
}

Related

Easy ways to increment with number and letters after checking DB

Using C# and ASP.NET
Lnna is based on values that the user inputs.
I can get those values.
Lnnai is the full form.
Last value 'i' should be incremented through 0-9,a-z and then A-Z. What would be the easiest way to look in DB for values and increment?
var Lnna = L + nn + a;
var ichars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
var i = ?
Examining an ASCII table yeilds
0-9 48-57
A-Z 65-90
a-z 97-122
It is much easier to increment a number than a letter so I converted the last letter to its ASCII value and incremented that then cast it back to a char and then toString.
private void Form2_Load(object sender, EventArgs e)
{
string input = "Lnnnai";
bool foundInDatabase = false;
//set your value after db query
if (foundInDatabase)
{ }//your code here
else
{
string s = input.Substring(input.Length - 1, 1);
s = IncrementCharacter(s);
Debug.Print(s);
string newString = input.Remove(input.Length - 1, 1);
newString += s;
Debug.Print(newString);
}
}
private string IncrementCharacter(String character)
{
int code = Char.ConvertToUtf32(character,0);
switch (code)
{
case 57:
return "A";
case 90:
return "a";
default:
code += 1;
return ((char)code).ToString();
}
}
to use Debug.Print import System.Diagnostics
This is the method I used. It works perfectly.
int tl = items.ShelfId;
var ttl = await _context.Shelfs.FirstOrDefaultAsync(b => b.ShelfId == tl);
var l = ttl.Name;
int tnn = items.CategoryId;
var ttnn = await _context.Categories.FirstOrDefaultAsync(b => b.CategoryId == tnn);
var nn = ttnn.Subject;
string a = items.AuthorLastName.Substring(0, 1);
var lnna = l + nn + a;
var ichars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".ToCharArray();
var currenti = _context.Items.Count(i => i.LibraryItemNumber.Contains(lnna));
if (currenti > 0 && currenti < 62)
{
var i = ichars[currenti];
var LNNAI = lnna + i;
items.LibraryItemNumber = LNNAI;
}
else if (currenti == 0)
{
var i = ichars[0];
var LNNAI = lnna + i;
items.LibraryItemNumber = LNNAI;
}
else
{
items.LibraryItemNumber = "Exceed";
}

Use i in variable name

So I have this kind of code (I'm assigning values to XAML elements
), which begs for a "for" loop.
Day1d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(1));
Day2d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(2));
Day3d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(3));
Day4d.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(4));
Day1t.Text = "°" + (myWeatherForecast.forecastlist[1].temp).ToString();
Day2t.Text = "°" + (myWeatherForecast.forecastlist[2].temp).ToString();
Day3t.Text = "°" + (myWeatherForecast.forecastlist[3].temp).ToString();
Day4t.Text = "°" + (myWeatherForecast.forecastlist[4].temp).ToString();
But all my attempts to include "i" in variable name failed miserably. Is there a way to achieve this?
You can create a loop where you iterate over the instances:
int counter = 1; // are you sure it shouldn't start at 0?
foreach (TextBox tb in new TextBox[] { Day1d, Day2d, Day3d, Day4d })
{
tb.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(counter));
counter++;
}
counter = 1;
foreach (TextBox tb in new TextBox[] { Day1t, Day2t, Day3t, Day4t })
{
tb.Text = "°" + (myWeatherForecast.forecastlist[counter].temp).ToString();
counter++;
}
You can't compose the name of the variable using another variable. The way to do this would be to create a List and then iterate over that List
var textBoxes1 = new List<TextBox> { Day1d, Day2d, Day3d, Day4d }
var textBoxes2 = new List<TextBox> { Day1t, Day2t, Day3t, Day4t }
foreach (var textbox in textBoxes1)
{
var index = textBoxes1.IndexOf(textBox) + 1;
textbox.Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(index));
}
foreach (var textbox in textBoxes2)
{
var index = textBoxes2.IndexOf(textBox) + 1;
textbox.Text = "°" + (myWeatherForecast.forecastlist[index].temp).ToString();
}
NOTE: You can solve this in different ways:
using arrays instead of lists
keeping your own counter, instead of doing IndexOf
using a for loop, instead of a foreach
Which one is better is mostly based on opinion (although my method is not the fastest, but it doesn't matter if you only have 4 items)
You can use FindName assuming you are using WPF.
Try:
for (int i = 1; i < 5; i++)
{
((TextBox)this.FindName("Day" + i + "d")).Text = string.Format("{0:dd/MM}", DateTime.Today.AddDays(i));
((TextBox)this.FindName("Day" + i + "t")).Text = "°" + (myWeatherForecast.forecastlist[i].temp).ToString();
}

check if linq operation is null before execution C#

I have a Win-form with 60 Radio-buttons. I want to get the Text from the checked radio-buttons with this code:
private void button1_Click_1(object sender, EventArgs e)
{
string[] boxes = new string[30];
string[] names = new string[30];
for (int i = 1; i < boxes.Length; i++)
{
var label = this.Controls.Find("lb" + i, true)[0];
var panelcontr = this.Controls.Find("panel" + i, true)[0] as Panel;
var panels = panelcontr;
var p = panels.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked).Text;
boxes[i] += p;
names[i] += label.Text;
tobeWritten += names[i] + boxes[i] + ",";
textBox1.Text = "Anamnese(" + tobeWritten + ")";
}
}
It works totally fine but the problem is, when just one radio-box is unchecked I get a warning during Debug. I know why the Warning appears but I want the Program not to stop.
What I'm asking is: Is it possible to create a MessageBox which appears, when I haven't checked a radioButton which e.g. says "You have to assign every button". I click the "OK"-Button and I am able to check the unchecked Button.
I tried with the suggestions from an other question at StackOverflow but no success because the function panels.Controls.OfType<RadioButton>() gets executed before the query.
You get a NullReferenceException here if there is no checked RadioButton:
var p = panels.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked).Text;
Because FirstOrDefault returns null since RadioButton is a reference type. Then you can't access it's Text property. So how to avoid that?
Store the result and check if it's null before you use it:
RadioButton firstCheckedRadioButton = panels.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
if(firstCheckedRadioButton != null)
{
string text = firstCheckedRadioButton.Text;
// ...
}
Your issue is here:
var p = panels.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked).Text;
If the result of the FirstOrDefault call is null, the Text call will throw a null reference exception. You can avoid this by splitting up the calls, so that you call FirstOrDefault, check whether the result is null, and then call Text only once you know the result is not null.
Would it help to replace
var p = panels.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked).Text;
with
var ch = panels.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
if (ch == null)
{
// show message box and break;
}
var p = ch.Text;
It works now with this code:
private void button1_Click_1(object sender, EventArgs e)
{
string[] boxes = new string[30];
string[] names = new string[30];
for (int i = 1; i < boxes.Length; i++)
{
var label = this.Controls.Find("lb" + i, true)[0];
var panelcontr = this.Controls.Find("panel" + i, true)[0] as Panel;
var panels = panelcontr;
var radiobutton = panels.Controls.OfType<RadioButton>()
.FirstOrDefault(r => r.Checked);
if(radiobutton==null)
{
MessageBox.Show("Check all Buttons!");
break;
}
boxes[i] += radiobutton.Text;
names[i] += label.Text;
tobeWritten += names[i] + boxes[i] + ",";
textBox1.Text = "Anamnese(" + tobeWritten + ")";
}
}

Adding a linked label for a list of features

I have a class that contains a list of features and I would like to add a link label for each item in that list. When doing this, I am not able to display all of the features, only the first feature. The smallest code snippet I have is:
foreach (var element in agol.orgServices.services)
{
var linkLabel = new LinkLabel();
linkLabel.Text = element.name + "\n";
linkLabel.Links.Add(new LinkLabel.Link(i, element.url.Length, element.url));
i = linkLabel.Text.Length;
ServicesTab.Controls.Add(linkLabel);
linkLabel.LinkClicked += (s, z) =>
{
System.Diagnostics.Process.Start(z.Link.LinkData.ToString());
};
}
The results I get are:
What I expect to get is something similar to this:
The second image is not individual labels added but a long text string instead. See code snippet below.
finalstring += element.name + "\n"
What am I doing wrong?
I solved it. The link labels were stacking on top of each other so I had to include an increment:
int i=0;
int yi = 30;
int y = 7;
int x = 2;
foreach (var element in agol.orgServices.services)
{
var linkLabel = new LinkLabel();
linkLabel.Name = element.name;
linkLabel.Text = element.name + "\n";
linkLabel.Location = new Point(x, y);
linkLabel.AutoSize = true;
linkLabel.Links.Add(new LinkLabel.Link(i, element.name.Length, element.url));
ServicesTab.Controls.Add(linkLabel);
linkLabel.LinkClicked += (s, z) =>
{
System.Diagnostics.Process.Start(z.Link.LinkData.ToString());
};
y += yi;
//finalServiceList += element.name + "\n";
}

Want to add a button that changes Celsius to Fahrenheit in a weather app

Recently I've created a weather application for windows phone 7 using C#. But it can show the temperature only in Celsius but I want to create a button in settings.xaml page that has an option to select either Celsius or Fahrenheit(At present i haven't created any button for this, the app will automatically shows the temperature in Celsius). Can anybody help me with this??? Thanks in advance for your hard work.
Below is the code i have used for it-:
private void ForecastDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Result == null || e.Error != null)
{
MessageBox.Show("Cannot load Weather Forecast!");
}
else
{
XDocument document = XDocument.Parse(e.Result);
var data1 = from query in document.Descendants("current_condition")
select new Forecast
{
observation_time = (string) query.Element("observation_time"),
temp_C = (string)query.Element("temp_C"),
temp_F = (string)query.Element("temp_F"),
weatherIconUrl = (string)query.Element("weatherIconUrl"),
weatherDesc = (string)query.Element("weatherDesc"),
humidity = (string)query.Element("humidity"),
windspeedMiles = (string)query.Element("windspeedMiles"),
windspeedKmph = (string)query.Element("windspeedKmph")
};
Forecast forecast = data1.ToList<Forecast>()[0];
var data2 = from query in document.Descendants("weather")
select new Forecast
{
date = (string)query.Element("date"),
tempMaxC = (string)query.Element("tempMaxC"),
tempMaxF = (string)query.Element("tempMaxF"),
tempMinC = (string)query.Element("tempMinC"),
tempMinF = (string)query.Element("tempMinF"),
weatherIconUrl = (string)query.Element("weatherIconUrl"),
};
List<Forecast> forecasts = data2.ToList<Forecast>();
for (int i = 0; i < forecasts.Count(); i++)
{
forecasts[i].date = DateTime.Parse(forecasts[i].date).ToString("dddd");
}
AddPanoramaItem(forecast,forecasts);
}
}
private void AddPanoramaItem(Forecast forecast, List<Forecast> forecasts)
{
PanoramaItemObject pio = new PanoramaItemObject();
pio.temperature = "Temperature: " + forecast.temp_C + " °C";
pio.observation_time = "Observ. Time: " + forecast.observation_time;
pio.windspeed = "Wind Speed: " + forecast.windspeedKmph + " Kmph";
pio.huminity = "Huminity: " + forecast.humidity + " %";
pio.weatherIconUrl = forecast.weatherIconUrl;
pio.forecasts = forecasts;
PanoramaItem panoramaItem = new PanoramaItem();
panoramaItem.Header = queries[query];
int index = queries[query].IndexOf(",");
if (index != -1) panoramaItem.Header =
queries[query].Substring(0, queries[query].IndexOf(","));
else panoramaItem.Header = queries[query];
panoramaItem.ContentTemplate =
(DataTemplate)Application.Current.Resources["ForecastTemplate"];
panoramaItem.Content = pio;
Panorama.Items.Add(panoramaItem);
query++;
if (query < queries.Count())
LoadForecast();
}
Use this formula
for Celcius to Farenhite
Tc = 5 (Tf-32) /9;
From Farenhite to Celcius
Tf = (9/5)*Tc+32
where Tc = temperature in degrees Celsius, Tf = temperature in degrees Fahrenheit

Categories

Resources