How to use variable outside for() and foreach() in C#? - c#

I don't know how to get a result from for to use in the foreach loop.
My code like:
List<string> lstNameImage = new List<string>();
for (int i = 0; i < lstImgAdded.Items.Count; i++)
{
string imgPath = lstImgAdded.Items[i].SubItems[0].Text;
lstNameImage.Add(imgPath);
}
foreach (var items in lstNameImage)
{
Image img = Image.FromFile(items[0].ToString()); // how to using img in before for loop?
}

You can change the below line
string imgPath = lstImgAdded.Items[i].SubItems[getRows].Text;
To just
string imgPath = lstImgAdded[i];
In foreach item variable already contains the list item what you are trying to get and so passing item would suffice
foreach (var item in lstNameImage)
{
Image img = Image.FromFile(item);
}

This code:
foreach (var items in lstNameImage)
{
Image img = Image.FromFile(item);
}
is functionally equivalent to:
foreach (int index = 0; index < lstNameImage.Count; index++)
{
var item = lstNameImage[index];
Image img = Image.FromFile(item);
}
Hence Rahul's solution.

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);
}
}

Write first and second column rows in listview inside each row in a text file

I'm using WinForms. In my form I have a listview and a button. When I click on the button the program writes all of the items in the listview into a text file. The problem is that I want the first and second column to be in one line.
Here is my code so far that i use to write to the text file:
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.WriteLine(item.Text);
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
My ListView
Problem output text file
How I want the text file to display
How about just
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.Write(item.Text + ": ");
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
It seems that your first cell "FirstPage" is the parent and all other items are sub items. Assuming you have only two columns below answer will work.
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.Write(string.Format("{0} :",item.Text));
for (int i = 1; i < item.SubItems.Count; i++)
{
if (i % 2 == 0)
{
sw.Write(string.Format("{0} :",item.SubItems[i].Text));
}
else
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
}
Alternative is; add each new row as a new item to the list view
string[] row = { "FirstPage", "$1.00" };
string[] row2 = { "SecondPage", "$1.00" };
var listViewItem = new ListViewItem(row);
listView1.Items.Add(listViewItem);
var listViewItem2 = new ListViewItem(row2);
listView1.Items.Add(listViewItem2);
and so on. You can iterate through a foreach loop for this adding and then use the below code which is flexible.
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
sw.Write(string.Format("{0} :",item.Text));
for (int i = 1; i < item.SubItems.Count; i++)
{
sw.WriteLine(item.SubItems[i].Text);
}
}
}
You can do it in a more elegant way:
var str = listView1.Items.Cast<ListViewItem>()
.Select(x => x.SubItems.Cast<ListViewItem.ListViewSubItem>())
.Select(x => string.Join(":", x.Select(s => s.Text)));
System.IO.File.WriteAllLines(#"d:\file.txt", str);
Note: If you want to limit the columns for example save only first two columns, you can select sub items at second line this way: x.SubItems.Cast<ListViewItem.ListViewSubItem>().Take(2)
You should iterate the List View items, concatenate each one of the sub items into each other and then add the concatenated string to the text file at the end... I have adapted your code:
using (StreamWriter sw = File.CreateText(DirectoryPath))
{
foreach (ListViewItem item in listView1.Items)
{
string strText = "";
//I'm not sure why you start at 1 and not 0, anyway:
for (int i = 1; i < item.SubItems.Count; i++)
{
strText+= " " + item.SubItems[i].Text;
}
sw.WriteLine(strText);
}
}

How to split items in Checkedlistbox having strings like A+B+C?

I have a checkedlistbox in which i am populating items like:
Biology+Physics+Chemistry
English+Urdu+Islamiyat
and so on. Now when i retrieve the values of selected items by splitting them on the basis of '+' sign, it gives me an output like:
Biology
Physics
ChemistryEnglish
Urdu
Islamiyat
Now you can look at the output as all values are right except ChemistryEnglish which have got concatenated. What should i be doing so to make this right? I want the output like this:
Biology
Physics
Chemistry
English
Urdu
Islamiyat
UPDATED
MY CODE IS:
String items = "";
string SQLString = "";
if (this.subjects_listbox.CheckedItems.Count != 0)
{
for (int i = 0; i < this.subjects_listbox.Items.Count; i++)
{
items += this.subjects_listbox.CheckedItems[i].ToString();
}
} //
String[] subNames = items.Split('+');
foreach (var item in subNames)
{
MessageBox.Show(item);
}
Finally i achieved my goal this by doing this:
String items = "";
string SQLString = "";
if (this.subjects_listbox.CheckedItems.Count != 0)
{
for (int i = 0; i < this.subjects_listbox.Items.Count; i++)
{
items += this.subjects_listbox.CheckedItems[i].ToString() + "+";
}
} //
String[] subNames = items.Split('+');
foreach (var item in subNames)
{
MessageBox.Show(item);
}
I think you need to split out the items in the CheckedListBox individually before you do what you are doing with items. Take the following code (assuming myCheckedListBox is the name of your CheckedListBox)
var subNameList = new List<string>();
foreach (var item in myCheckedListBox.Items)
{
foreach (string subName in (item.ToString().Split('+'))
{
subNameList.Add(subName);
}
}
This will result in you having a list of strings at the end in subNameList. You may want to use myCheckedListBox.CheckedItems rather than myCheckedListBox.Items depending on your use case.
I achieved my goal by doing this:
String items = "";
string SQLString = "";
if (this.subjects_listbox.CheckedItems.Count != 0)
{
for (int i = 0; i < this.subjects_listbox.Items.Count; i++)
{
items += this.subjects_listbox.CheckedItems[i].ToString() + "+";
}
}
String[] subNames = items.Split('+');
foreach (var item in subNames)
{
MessageBox.Show(item);
}

Read last n elements of an XML file with Linq XDocument

I am using the follow Code to read an XML file:
XDocument doc = XDocument.Load(xmlPath);
foreach (var node in doc.Descendants("LogInfo"))
{
ListViewItem item = new ListViewItem(new string[]
{
node.Element("MailBox").Value,
node.Element("LastRun").Value,
});
listViewHome.Items.Add(item);
}
How can I change this Code to receive just the last "n" number of elements from that XML file?
Thanks in advance.
You could do this:
var nodes = doc.Descendants("LogInfo");
foreach (var node in nodes.Skip(Items.Count() - n))
{
...
}
Or this:
var nodes = doc.Descendants("LogInfo");
foreach (var node in nodes.Reverse().Take(n).Reverse())
{
...
}
If you're feeling adventurous, you could also write your own extension method which should be more efficient than either of these. Here's my quick and dirty solution:
public static IEnumerable<T> TakeFromEnd<T>(this IEnumerable<T> items, int n)
{
var arry = new T[n];
int i = 0;
foreach(var x in items)
{
arry[i++ % n] = x;
}
if (i < n)
{
n = i;
i = 0;
}
for (int j = 0; j < n; j++)
{
yield return arry[(i + j) % n];
}
}
var nodes = doc.Descendants("LogInfo");
foreach (var node in nodes.TakeFromEnd(n))
{
...
}
XDocument doc = XDocument.Load(xmlPath);
var logs = doc.Descendants("LogInfo");
var logsCount = logs.Count();
foreach (var node in logs.Skip(logsCount - n).Take(n))
{
ListViewItem item = new ListViewItem(new string[]
{
node.Element("MailBox").Value,
node.Element("LastRun").Value,
});
listViewHome.Items.Add(item);
}
And here is XPath solution, which will enumerate xml once
var xpath = String.Format("//LogInfo[position()>last()-{0}]", n);
foreach (var log in doc.XPathSelectElements(xpath))
{
ListViewItem item = new ListViewItem(new string[]
{
(string)log.Element("MailBox"),
(string)log.Element("LastRun")
});
listViewHome.Items.Add(item);
}

Use of unassigned local variable

While I am trying to debug this code (in C# WinForms), it shows an error
"use of unassigned local variable" at 'arrlist[i]'
Since I'm comparing it with a database variable, I cannot initialize the size of the array.
This is the code:
if (count != 0)
{
OleDbCommand cmd1 = new OleDbCommand(
"select seat_no, booking_date, show_time "+
"from tickets "+
"where ticket_no = (select max(ticket_no) from tickets)", c);
OleDbDataReader oledb1 = cmd1.ExecuteReader();
oledb1.Read();
string retr_seats = oledb1.GetString(0);
char comma = ',';
string[] strarray = retr_seats.Split(comma);
int ticket_length = strarray.Length;
string[] arrlist;
int i = 0;
foreach(var control in this.Controls)
{
if(control is Label)
{
arrlist[i] = control.ToString();
i++;
}
}
for(var j=0;j<=ticket_length;j++)
{
for (var k = 0; k <= i-1; k++)
{
if (arrlist[k].Contains(strarray[j]))
{
MessageBox.Show(strarray[j]);
}
}
}
}
Please help me
You need to initialize the variable arrlist. Change this line:
string[] arrlist;
To this:
string[] arrlist = new string[this.Controls.Count]; // Must be big enough.
Or better, use a dynamically sized container such as a List<string>.
List<string> arrList = new List<string>();
foreach(var control in this.Controls)
{
if(control is Label)
{
arrlist.Add(control.ToString());
}
}
Or use LINQ to get the result directly:
string[] arrlist = this.Controls
.OfType<Label>()
.Select(control => control.ToString())
.ToArray();
Change your array to a list, and add values to the list. You can then index the list elements directly, or if you need an array, you can use .ToArray() on the list instance.
Also note that your for loop over j will go out of bounds on strarray unless you change the comparison to < ticket_length from <= ticket_length.
...
var arrlist = new List<string>();
foreach(var control in this.Controls)
if(control is Label)
{
arrlist.Add(control.ToString());
}
for(var j=0;j<ticket_length;j++)
for (var k = 0; k < arrlist.Count; k++)
if (arrlist[k].Contains(strarray[j]))
MessageBox.Show(strarray[j]);
string[] arrlist;
....
arrlist[i] = control.ToString();
you lost initialization like: arrlist = new string[count];
The problem is that arrlist is defined, but not initialized.
You need to initialize it, like this:
string[] arrlist = new arrlist[size];
If you don't know how big it will be, it is better to use a list:
List<string> arrlist = new List<string>();
and to add items: arrlist.add("some string");

Categories

Resources