listview thumbnails repeating c# - c#

I'm trying to populate a listview box with thumbnails you can select to bring up a preview.
The listview populates with the correct amount of images, tagged with the correct filepath, but the thumbnail for each is a repetition of the first indexed image in the linked imagelist. (see attached code)
private void PopulateList()
{
DirectoryInfo dir = new DirectoryInfo(#"C:\Temp\Snapshots");
this.listImages.View = View.LargeIcon;
this.imageList1.ImageSize = new Size(140, 100);
this.listImages.LargeImageList = this.imageList1;
int j = 0;
foreach (FileInfo file in dir.GetFiles())
{
try
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
item.Tag = file.FullName;
this.imageList1.Images.Add(Image.FromFile(file.FullName));
this.listImages.Items.Add(item);
j = j++;
//fixed by changing above line to
//j = (j+1);
}
catch
{
}
}
}
Any assistance would be greatly appreciated, I feel like I'm missing something really simple...
Thanks.
EDIT: Fix in code as comment

Related

Load images from file c#

this is my code this is showing only one image data multiple times in list view instead of showing all images data.
public void loadImages()
{
string[] liness = File.ReadAllLines("Food.txt");
for (int a = 0; a < liness.Length; a++)
{
string[] check = liness[a].Split(',');
listView.Items.Clear();
foreach (var line in liness)
{
ListViewItem item = new ListViewItem(check[2]);
listView.Items.Add(item);
}
}
}
You are clearing listview in each loop iteration. Put listView.Items.Clear(); line out of loop. Also there is no need of foreach (var line in liness) inner loop. Remove this foreach loop.
Try this
public void loadImages()
{
listView.Items.Clear();
string[] liness = File.ReadAllLines("Food.txt");
for (int a = 0; a < liness.Length; a++)
{
string[] check = liness[a].Split(',');
ListViewItem item = new ListViewItem(check[2]);
listView.Items.Add(item);
}
}

Only one item appearing on Listview

I need to make a list of products with their respective icons above but it only appears one item. There are 20 products total. How can I insert the other 19 items?
Code:
ImageList imageList = new ImageList();
prodview.LargeImageList = imageList;
while (i < 20)
{
var json = c.DownloadString(url + (i + 1).ToString());
var image = c.DownloadData(urlicon + (i + 1).ToString());
var dataDict = JsonConvert.DeserializeObject<List<Data>>(json);
ListViewItem item = new ListViewItem();
foreach (var data in dataDict)
item.Text = data.name;
imageList.ImageSize = new Size(100, 100);
imageList.Images.Add(i.ToString(), new Bitmap(new MemoryStream(image)));
item.ImageIndex = i;
prodview.Items.Add(item);
i++;
}
This version of the code already works. Answer below.
Your logic has issues
for i = 0 to 19 ..
download data/string create new list item create new image list
foreach item in datadict set item.text
add 1 image to imagelist
for all items currently in image list (aka 1) add it to prodview
rpt.
so you only end up with 1 item, as you remade item list each time, and each variable each time.
you almost certainly want something like:
ImageList imageList = new ImageList();
to be before the while loop. The below doesnt need to be in a loop either - otherwise its repeating.
prodview.LargeImageList = imageList;
item.ImageIndex = i;
prodview.Items.Add(item);
There maybe other issues - such as im not convinced about the images but.. start there
Adjusting my code some..
Your code probably should end up like
ImageList imageList = new ImageList();
prodview.LargeImageList = imageList;
while(i <20)
{
var json = c.DownloadString(url + (i + 1).ToString());
var image = c.DownloadData(urlicon + (i + 1).ToString());
var dataDict = JsonConvert.DeserializeObject<List<Data>>(json);
ListViewItem item = new ListViewItem();
// not sure what you were trying to do here as it would always end up with the last name..
// foreach (var data in dataDict)
// item.Text = data.name;
item.Text = "item "+i; // giving it a name
imageList.ImageSize = new Size(100, 100);
imageList.Images.Add(i.ToString(), new Bitmap(new MemoryStream(image)));
item.ImageIndex = i;
prodview.Items.Add(item);
i++;
}

How we count how many multiple selection in chart area?

I want to count the multiple selections in chart area.As an example user can marked multiple selection as this picture,Multiple selected chart.So how I count how many multiple selection in this chart.This is MSchart in windowsform by using C#.
my multiple selection code as follows;
SizeF rangeOfCurve = SizeF.Empty;
List<SizeF> ranges = new List<SizeF>();
List<int> selectedIndices = new List<int>();
private void chart1_SelectionRangeChanged(object sender, CursorEventArgs e)
{
ranges.Add(rangeOfCurve);
selectedIndices.Union(collectDataPoints(chart1.Series[0],rangeOfCurve.Width, rangeOfCurve.Height)).Distinct();
StripLine sl = new StripLine();
sl.BackColor = Color.FromArgb(255, Color.LightSeaGreen);
sl.IntervalOffset = Math.Min(rangeOfCurve.Width, rangeOfCurve.Height);
sl.StripWidth = Math.Abs(rangeOfCurve.Height - rangeOfCurve.Width);
chart1.ChartAreas[0].AxisX.StripLines.Add(sl);
}
List<int> collectDataPoints(Series s, double min, double max)
{
List<int> hits = new List<int>();
for (int i = 0; i < s.Points.Count; i++)
if (s.Points[i].XValue >= min && s.Points[i].XValue <= max) hits.Add(i);
return hits;
}
private void chart1_SelectionRangeChanging(object sender, CursorEventArgs e)
{
rangeOfCurve = new SizeF((float)e.NewSelectionStart, (float)e.NewSelectionEnd);
}
This is my code for export those selected data to new .csv file.In here I added button click event then selected area data to export another .csv file.but I want to say I can add multiple selection in chart area but data is exported only last selected part only.how can I got all multiple selection data.this is code for getting one selected area data to another .csv file.
private void btnExport_Click(object sender, EventArgs e)
{
List<Graph> ObservingData = new List<Graph>(); // List to store all available Graph objects from the CSV
int index = 0;
using (StreamWriter sw = new StreamWriter(#"D:\CSVFile\NEWFile\Export\NewFile.csv"))
{
// Loops through each lines in the CSV
foreach (string line in System.IO.File.ReadAllLines(pathToCsv))
{
// here line stands for each line in the csv file
string[] CsvLine = line.Split(',');
// creating an object of type Graph based on the each csv line
// and adding them to the List<Graph>
Graph Instance1 = new Graph();
if (index == 0)
{
sw.WriteLine(line);
}
else
{
//Add the code here..**
if (((chart1.ChartAreas[0].CursorX.SelectionStart))<=index && ( index<= (chart1.ChartAreas[0].CursorX.SelectionEnd)))
{
sw.WriteLine(line);
}
}
index++;
}
sw.Close();
}
MessageBox.Show("Data are copied to the new .CSV file");
}
If you can give any help to solve this.I am so much thankful to you.
Assuming you have added StripLines to mark selections, here is an example of how you can collect the DataPoints from these StripLines:
Let's create a List<> of point list:
selectionPoints = new List<List<DataPoint>>();
Now we can collect the DataPoints like this:
List<List<DataPoint>> GetSelectedPoints(ChartArea ca, Series S)
{
selectionPoints = new List<List<DataPoint>>();
foreach (var sl in ca.AxisX.StripLines)
{
List<DataPoint> points = new List<DataPoint>();
points = S.Points.Select(x => x)
.Where(x => x.XValue >= sl.IntervalOffset
&& x.XValue <= (sl.IntervalOffset + sl.StripWidth)).ToList();
selectionPoints.Add(points);
}
return selectionPoints;
}
And now we can do things with the DataPoints like color them..:
foreach (var pointList in selectionPoints)
{
foreach (var dp in pointList) dp.Color = Color.Red;
}
.. or export them:
string filePath = "D:\\demo.csv";
StringBuilder sb = new StringBuilder();
foreach (var pointList in selectionPoints)
{
foreach (var dp in pointList)
sb.Append(dp.XValue + "," + dp.YValues[0] + ";"); // pick your format!
}
File.WriteAllText(filePath, sb.ToString());

Remove a checkbox that is being created dynamically in a loop

I have a bunch of code that dynamicly creates some controls. It looks in a folder and lists the filenames in it. For each file in the folder it creates a checklistbox item, listbox item and two checkboxes. This is working great and as intended:
private void getAllFiles(string type)
{
try
{
string listPath = "not_defined";
if (type == "internal_mod")
{
int first_line = 76;
int next_line = 0;
int i = 0;
CheckBox[] chkMod = new CheckBox[100];
CheckBox[] chkTool = new CheckBox[100];
listPath = this.internalModsPath.Text;
string[] filesToList = System.IO.Directory.GetFiles(listPath);
foreach (string file in filesToList)
{
if (!internalModsChkList.Items.Contains(file))
{
internalModsChkList.Items.Add(file, false);
string fileName = Path.GetFileName(file);
internalModNameList.Items.Add(fileName);
//-----------------
// Draw Checkboxes
//-----------------
chkMod[i] = new CheckBox(); chkTool[i] = new CheckBox();
chkMod[i].Name = "modChk" + i.ToString(); chkTool[i].Name = "modChk" + i.ToString();
//chkMod[i].TabIndex = i; //chkTool[i].TabIndex = i;
chkMod[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top); chkTool[i].Anchor = (AnchorStyles.Left | AnchorStyles.Top);
chkMod[i].Checked = true; chkTool[i].Checked = false;
chkMod[i].AutoCheck = true; chkTool[i].AutoCheck = true;
chkMod[i].Bounds = new Rectangle(549, first_line + next_line, 15, 15); chkTool[i].Bounds = new Rectangle(606, first_line + next_line, 15, 15);
groupBox7.Controls.Add(chkMod[i]); groupBox7.Controls.Add(chkTool[i]);
//-----------------
next_line += 15;
i++;
}
}
}
Now my problem is that I also want the user to be able to delete all these thing again based on the checklistbox' checked items.. I have no problems deleting the items in the checklistbox or the items in the listbox, but I want to remove the two checkboxes I create too ..
This is what I got to remove the items in the checklistbox, and the listbox
private void internalModListDel_btn_Click(object sender, EventArgs e)
{
int count = internalModsChkList.Items.Count;
for (int index = count; index > 0; index--)
{
if (internalModsChkList.CheckedItems.Contains(internalModsChkList.Items[index - 1]))
{
internalModsChkList.Items.RemoveAt(index - 1);
internalModNameList.Items.RemoveAt(index - 1);
groupBox7.Controls.Remove(modChk[index - 1]);
}
}
}
As you can see I have also tried to write something to remove the checkbox but it doesn't work and I have no idea how to make it work
Can you assist ?
Try using UserControls.
Use the ListBox controller to show those UserControls,
The user control can be built with those checkboxes, and the labels you want .
Another suggestion is to bind this list to an ObservableCollection which will contain the UserContorols you have created.
This way, it will be much more simlpe to add/remove/change the items inside.

C# ImageList won't display images

I've been trying to figure out why my imageList won't render out my images when my form runs, I am using the following code...
public void renderImageList()
{
int selection = cboSelectedLeague.SelectedIndex;
League whichLeague = (League)frmMainMenu.allLeagues[selection];
string index = cboSelectedLeague.SelectedItem.ToString();
if (whichLeague.getLeagueName() == index)
{
foreach (Team t in allTeams)
{
Image teamIcon = Image.FromFile(#"../logos/" + t.getTeamLogo());
imgLstIcons.Images.Add(teamIcon);
}
}
else
{
MessageBox.Show("Something went wrong..." + whichLeague.getLeagueName() + " " + index + ".");
}
}
The method is fired when the user changes the index of my combo box, I know the program gets the correct path as I used a message box to display the path each path returned as I expected it to.
Am I missing something from my code to draw the image to the box?
Alex.
After adding all images to the ImageList, you should add all the items to the ListView as well:
for (int j = 0; j < imgLstIcons.Images.Count; j++)
{
ListViewItem item = new ListViewItem();
item.ImageIndex = j;
lstView.Items.Add(item);
}
source: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/876b6517-7306-44b0-88df-caebf3b1c10f/
You can also use a FlowLayoutPanel and dynamically create PictureBox elements, one for each Image, and not use ImageLists and ListViews at all. It depends on the type of UI you want.

Categories

Resources