I want to show images from resources in pictureboxes randomly - c#

With a List of 6 images names and a list of six picture boxes, I want to show images from resources in picture boxes randomly.
This code is not working. Just empty picture boxes.... Why?
List<PictureBox> box = new List<PictureBox>();
box.Add(pictureBox1);
box.Add(pictureBox2);
box.Add(pictureBox3);
box.Add(pictureBox4);
box.Add(pictureBox5);
box.Add(pictureBox6);
List<string> name = new List<string>();
name.Add("_1.jpg");
name.Add("_2.jpg");
name.Add("_3.jpg");
name.Add("_4.jpg");
name.Add("_5.jpg");
name.Add("_6.jpg");
Random r = new Random();
for (int i = 0; i < box.Count; i++)
{
int rand = r.Next(0, 6);
String imgname = name[rand];
object Ob= Properties.Resources.ResourceManager.GetObject(imgname);
box[i].Image = Ob as Image;
}

I modified your code:
List<PictureBox> box = new List<PictureBox>();
box.AddRange(new PictureBox[]
{
pictureBox1,
pictureBox2,
pictureBox3,
pictureBox4,
pictureBox5,
pictureBox6,
});
List<string> name = new List<string>()
{
"_1.jpg",
"_2.jpg",
"_3.jpg",
"_4.jpg",
"_5.jpg",
"_6.jpg"
};
Random r = new Random();
for (int i = 0; i < this.Count; i++)
{
var rm = new System.Resources.ResourceManager(((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()).GetName().Name + ".Properties.Resources", ((System.Reflection.Assembly)System.Reflection.Assembly.GetExecutingAssembly()));
this[i].Image = (Bitmap)rm.GetObject(name[r.Next(0, 6)]);
}

Your resources typically do not include the file extension, so try just using the name of the image.
name.Add("_1");
name.Add("_2");
Personally, I would not include an underscore in the file names — might complicate things.

Related

how to color unstructured grid (.vtu) in vtk?

My whole source code is present here including block.vtu file for testing purpose. I will discuss important functions here.
This code can color *.vtp, *.vtk.
But same code fails to color *.vtu.
I have list of vtkactors. And I specify which actor to set properties from.
This code which gets all column names from an actor:
public static List<string> getColumns(int actorIndex)
{
List<string> colums = new List<string>();
vtkActor actor = actors[actorIndex];
var output = actor.GetMapper().GetInputAsDataSet();
var cell = output.GetCellData();
for (int i = 0; i < cell.GetNumberOfArrays(); i++)
{
var colm = cell.GetArrayName(i);
if (colm != null) colums.Add(colm);
}
return colums; //['CU_OK','D1','Domain','IJK','IX','IY'...]
}
This code colors the model of specific column:
public static void setColors(int actorIndex, string column)
{
List<string> colums = new List<string>();
vtkActor actor = actors[actorIndex];
var output = actor.GetMapper().GetInputAsDataSet();
var colors = vtkUnsignedCharArray.New();
colors.SetNumberOfComponents(3);
colors.SetName("Colors");
var cell = output.GetCellData();
for (int i = 0; i < cell.GetNumberOfArrays(); i++)
{
var cells = cell.GetArray(i);
if (cells == null) continue;
if (column != cell.GetArrayName(i)) continue;
for (int j = 0; j < cells.GetNumberOfTuples(); j++)
{
var c = color_range((cells.GetComponent(i, j) / cell.GetArray(i).GetRange()[1]) * 100);
var R = c.R;
var G = c.G;
var B = c.B;
colors.InsertNextTuple3((double)R, (double)G, (double)B);
colors.InsertNextTuple3((double)R, (double)G, (double)B); //even tried with and without inserting second tuple
}
}
output.GetPointData().SetScalars(colors); //even tried with GetCellData(), but no luck
}
This code gets range(min,max) of values from specific column:
public static double[] getRange(int actorIndex, string column)
{
List<string> colums = new List<string>();
vtkActor actor = actors[actorIndex];
var output = actor.GetMapper().GetInputAsDataSet();
var cell = output.GetCellData();
for (int i = 0; i < cell.GetNumberOfArrays(); i++)
{
var colm = cell.GetArrayName(i);
var arr = cell.GetArray(i);
if (column == colm)
{
if (arr == null) return null;
return arr.GetRange(); // new double[] { min, max }
}
}
return null;
}
ACTUAL OUTPUT for VTP and VTK (GOOD):
The result is fine. This is how drillholes are shown in by my code.
EXPECTED OUTPUT for VTU (GOOD):
See how its colored. This is what PARAVIEW software can show:
ACTUAL OUTPUT for VTU (BAD):
This is how my code show that model:
I also tried:
I tried following question, but vtu color has no effect.
I tried cell data too instead of point data.
I also tried lookup table, it do shows with color scalebar but has no effect on model color.
The strange things are that:
all vtp files work (to color)and all vtu files fails
vtu file show colorful fine on paraview, but not in my code
I am not sure if this is a proper solution, but it might work if you create a new mapper at the end of the setColors function.
output.GetPointData().SetScalars(colors);
+ vtkDataSetMapper mapper = vtkDataSetMapper.New();
+ mapper.SetInput(output);
+ actor.SetMapper(mapper);
}

Replacing labels c# wpf

created a sports table that shows different statistics sorted by one property. When sorting for a different property I created completely new labels that just sit on top of the old ones instead of replacing them.
This is ran when a button is pressed:
private void Points_Order(object sender, RoutedEventArgs e)
{
List<Team> leagueTeams = new List<Team>();
using (StreamReader sr = new StreamReader("TXT1.txt"))
{
using (JsonReader jr = new JsonTextReader(sr))
{
JsonSerializer js = new JsonSerializer();
leagueTeams = js.Deserialize<List<Team>>(jr);
}
}
List<Team> sortedList = leagueTeams.OrderByDescending(o => o.points).ToList(); //orders the keagueTeams list by points and stores in a new list using linq
List<Label> TeamLabels = new List<Label>(); //makes list of labels that show the teams
List<string> Names = new List<string>(); //Creates a list for the names
List<Label> gamesPlayedLabels = new List<Label>();
List<int> GamesPlayed = new List<int>();
foreach (var properties in sortedList)
{
Names.Add(properties.name);//adds the name of each object into the Names list
GamesPlayed.Add(properties.gamesPlayed);
}
for (int i = 0; i < 20; i++)
{
string nameLab = Names[i];
TeamLabels.Add(new Label { Height = 100, Width = 100, Content = nameLab }); //sets position of the name labels
Canvas.SetLeft(TeamLabels[i], 0);
Canvas.SetTop(TeamLabels[i], (i * 19) + 19);
canvas1.Children.Add(TeamLabels[i]);
string played = Convert.ToString(GamesPlayed[i]);
gamesPlayedLabels.Add(new Label { Height = 100, Width = 100, Content = played });
Canvas.SetLeft(gamesPlayedLabels[i], 112);
Canvas.SetTop(gamesPlayedLabels[i], (i * 19) + 19);
canvas1.Children.Add(gamesPlayedLabels[i]);
}
}
When a second button is pressed the exact same code is ran but apart from
List<Team> sortedList = leagueTeams.OrderByDescending(o => o.points).ToList()
it is
List<Team> sortedList = leagueTeams.OrderBy(o => o.name).ToList();
so the question is can you replace existing labels so the table can be sorted?

C# Chart - multiple curves but color gets overwritten

So i'm displaying multiple curves in my chart. However, when i generate a random color, all the other curves will get this color too.
int fileIndex=0;
Random r = new Random();
foreach (var i in graphContainer)
{
fileIndex++;
var series = new Series
{
Name = legendNames[fileIndex],
Color = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)),
IsVisibleInLegend = true,
IsXValueIndexed = false,
ChartType = SeriesChartType.Line
};
foreach (var j in i)
{
series.Points.AddXY (j.Item2, j.Item1);
}
chart.Invalidate ();
chart.Series.Add (series);
}
Note: all the curves except one has the same values, but you get the idea.
Why is my curves getting the same colors?
Entire function:
private void generateWaveformsFromFileBtn_Click(object sender, EventArgs e)
{
int fileIndex = -1;
string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\WaveForms\";
string filter = "*.csv";
string[] filePath = Directory.GetFiles(folder, filter);
List<string> legendNames = new List<string>();
List<Tuple<double, double>> graph = new List<Tuple<double, double>>();
List<List<Tuple<double, double>>> graphContainer = new List<List<Tuple<double, double>>>();
chart.Series.Clear();
foreach(var fileName in filePath) {
legendNames.Add(Path.GetFileName(fileName));
using (TextFieldParser csvParser = new TextFieldParser(fileName))
{
csvParser.SetDelimiters (new string[] { ";" });
csvParser.ReadLine ();
while (!csvParser.EndOfData)
{
string[] fields = csvParser.ReadFields();
double current = Double.Parse(fields[0]);
double inductance = Double.Parse(fields[1]);
graph.Add (new Tuple<double,double>(current, inductance));
}
graphContainer.Add(graph);
}
}
Random r = new Random();
foreach (var i in graphContainer)
{
fileIndex++;
var series = new Series
{
Name = legendNames[fileIndex],
Color = Color.FromArgb(r.Next(0, 256), r.Next(0, 256), r.Next(0, 256)),
IsVisibleInLegend = true,
IsXValueIndexed = false,
ChartType = SeriesChartType.Line
};
foreach (var j in i)
{
series.Points.AddXY (j.Item2, j.Item1);
}
chart.Invalidate ();
chart.Series.Add (series);
}
}
Suggestion: (?)
You have already posted one solution:
Before adding new data in a loop, make sure the old data are deleted. You do it by creating a new instance:
graph = new List<Tuple<double, double>>();
This is a valid approach.
But for completeness' sake let's look at the more direct aproach as well:
graph.Clear();
This clears the data from the list object. But you are adding the graph to the graphContainer list like this:
graphContainer.Add(graph);
which means that the very object gets put into the list which, before the next loop, will be cleared. This is a common mistake. The solution is simple: Don't add the graph object itself into the graphContainer list but a copy of it :
graphContainer.Add(graph.ToList());
The ToList() call is a simple way to create a copy of a List<T>.
As for the post you linked to: The old post is strictly about runtime performance. And not about creating copies of the lists.
But even there, the recommended way to do it is depending on whether you can predict the number of elements you will put in each list.
If you can predict it and if it is somewhat largish, let's say more than a few hundred of large or a many thousands of smallish elements you should tell the list which capacity it should reserve.
This avoids multiple growing pains. After a Clear() the Capacity is retained, avoiding new allocations.
Your elements (Tuples) are small, so you probably don't need to worry about the list growing performance..
As suggested by user #Taw, i forgot to create a new instance of the graph or empty it, between runs.
graph = new List<Tuple<double, double>>(); // <-- solved it
while (!csvParser.EndOfData)
{
string[] fields = csvParser.ReadFields();
...
}
EDIT:
Do not use yourList.Clear() see here why: https://stackoverflow.com/a/35848659/2902996

How do I make List of Lists? And then add to each List values?

class ExtractLinks
{
WebClient contents = new WebClient();
string cont;
List<string> links = new List<string>();
List<string> FilteredLinks = new List<string>();
List<string> Respones = new List<string>();
List<List<string>> Threads = new List<List<string>>();
public void Links(string FileName)
{
HtmlDocument doc = new HtmlDocument();
doc.Load(FileName);
foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
HtmlAttribute att = link.Attributes["href"];
if (att.Value.StartsWith("http://rotter.net/forum/scoops1"))
{
links.Add(att.Value);
}
}
for (int i = 0; i < links.Count; i++)
{
int f = links[i].IndexOf("#");
string test = links[i].Substring(0, f);
FilteredLinks.Add(test);
}
for (int i = 0; i < FilteredLinks.Count; i++)
{
contents.Encoding = System.Text.Encoding.GetEncoding(1255);
cont = contents.DownloadString(FilteredLinks[i]);
GetResponsers(cont);
}
}
private void GetResponsers(string contents)
{
int f = 0;
int startPos = 0;
while (true)
{
string firstTag = "<FONT CLASS='text16b'>";
string lastTag = "&n";
f = contents.IndexOf(firstTag, startPos);
if (f == -1)
{
break;
}
int g = contents.IndexOf(lastTag, f);
startPos = g + lastTag.Length;
string responser = contents.Substring(f + firstTag.Length, g - f - firstTag.Length);
foreach (List<string> subList in Threads)
{
}
}
}
}
I created this variable :
List<List<string>> Threads = new List<List<string>>();
The first thing I don't know yet how to do is how to create inside Threads number of Lists according to the FilteredLinks.Count inside the Links method.
Second thing is in the GetResponsers method I did:
foreach (List<string> subList in Threads)
{
}
But what I want is that first time it will add all the values from variable responser to the first List in Threads. Then when it's getting to the break; it stop then and then in the Links methods its calling GetResponsers(cont); again this time I want that all the values in responser to be added to the second List in Threads.
I know that each time it's getting to the break; it will get the next FilteredLink from FilteredLinks.
How do I create number of Lists in Threads according to the FilteredLinks.Count?
How do I make the code in GetResponsers to add the responser ?
You don't need to specify the count for the number of lists in Threads, since it is a list, you can simply keep adding lists to it. So the first part is correct where you are declaring it.
The second part --> Your calling method will change. Look below for the calling method.
The third part --> Change private void GetResponsers(string contents) to private void GetResponsers(List threadList, string contents). Look below for implementation change.
Also the loop will look like this then
//other code you have
List<List<string>> Threads = new List<List<string>>();
public void Links(string FileName)
{
// ...other code you have
for (int i = 0; i < FilteredLinks.Count; i++)
{
threads.Add(new List<string>);
contents.Encoding = System.Text.Encoding.GetEncoding(1255);
cont = contents.DownloadString(FilteredLinks[i]);
GetResponsers(threads[threads.Count - 1], cont);
}
}
private void GetResponsers(List<string> threadList, string contents)
{
int f = 0;
int startPos = 0;
while (true)
{
string firstTag = "<FONT CLASS='text16b'>";
string lastTag = "&n";
f = contents.IndexOf(firstTag, startPos);
if (f == -1)
{
break;
}
int g = contents.IndexOf(lastTag, f);
startPos = g + lastTag.Length;
string responser = contents.Substring(f + firstTag.Length, g - f - firstTag.Length);
threadList.Add(responser);
}
}
PS: Please excuse the formatting.
How do i make List of Lists ? And then add to each List values?
The following codesnippet demonstrates you, how to handle List<List<string>>.
List<List<string>> threads = new List<List<string>>();
List<string> list1 = new List<string>();
list1.Add("List1_1");
list1.Add("List1_2")
threads.Add(list1);
List<string> list2 = new List<string>();
list1.Add("List2_1");
list1.Add("List2_2")
list1.Add("List2_3")
threads.Add(list2);
How do i create number of Lists in Threads according to the
FilteredLinks.Count ?
for(int i = 0; i < FilteredLinks.Count; i++)
{
var newList = new List<string>();
newList.Add("item1"); //add whatever you wish, here.
newList.Add("item2");
Threads.Add(newList);
}
I'm afraid I can't help you with Question #2, since I don't understand what you try to achieve there exactly.

Assigning a button tag based on random items from an array

{
var buttonnameString = new List<string> { "button1", ... , "button12" };
for(int i = 0; i < 12; i++)
{
// Random car assignment to button
Random myRandom = new Random();
var carString = new List<string> { "Camaro", ... , "Model T" };
int index = myRandom.Next(carString.Count);
var name = carString[index];
carString.RemoveAt(index);
Tag = name.ToString();
}
}
In advance, thank you for any help that is provided. I'm a first year C# student so I know I have a lot to learn, but I've exhausted the extent of my google skills on trying to get this to work.
What I'm trying to do, is make a matching program. This program will have 12 buttons, labeled "button1", "button2"....etc. When the button is clicked, it will display it's tag, which is provided from a random array. I've gotten the random feature to work on assigning only a single buttons tag. Where I'm hung up at, is repeating this to all the buttons in a groupbox. I've tried the foreach venue, but couldn't get it to work successfully. Eventually I tried other methods as well. Below is where I've stopped at as I'm unsure on where to go. The two major questions that I have are
How do I assign the random string to a wildcard button tag?
What is the best way to accomplish randomly assigning 12 car names, to 12 buttons? The use of two arrays?
Try this:
{
var numOfButtons = 12;
var matchingButtonIndex = 0;
// Random car assignment to button
Random myRandom = new Random();
var buttons = new List<Button> { button1, ... , button12 };
var carString = new List<string> { "Camaro", ... , "Model T" };
while (matchingButtonIndex < numOfButtons)
{
int index = myRandom.Next(carString.Count);
var name = carString[index];
if (name != null)
{
buttons[matchingButtonIndex].Tag = name;
carString[index] = null;
matchingButtonIndex = matchingButtonIndex + 1;
}
}
}
Notice I have changed the button names array to an array of buttons. I have also emptied out the carString as I find unused car names.
Iterating over buttons is easy when you iterate through the form's Controls
var carString = new List<string> { "Camaro", "Mini Cooper", "Porsche 944", "Ford Focus", "Chevy Blazer", "Model T", "Camaro", "Mini Cooper", "Porsche 944", "Ford Focus", "Chevy Blazer", "Model T" };
foreach(Control c in Controls)
{
if (c is Button)
{
Random myRandom = new Random();
int index = myRandom.Next(carString.Count);
c.Tag = carString[index];
}
}

Categories