c# move item in listbox up and down - c#

I got a windows form application with a listbox that display content, I wanna be able to move the items from the listbox up and down, when a button is clicked. at the moment the items in the list box stored are in text file, which is loaded into configuration class when the application start. How would I move the items up/down and change the order in the text file?
my main application form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace company1
{
public partial class Form1 : Form
{
List<Configuration> lines = new List<Configuration>();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.listBox1.Items.Clear();
//Read in every line in the file
using (StreamReader reader = new StreamReader("file.txt"))
{
string line = reader.ReadLine();
while (line != null)
{
string[] array = new string[] { "\\n" };
string[] parts = new string[3];
parts = line.Split(array, StringSplitOptions.RemoveEmptyEntries);
lines.Add(new Configuration(parts[0], int.Parse(parts[1]), int.Parse(parts[2])));
line = reader.ReadLine();
}
}
listBox1.DataSource = lines;
listBox1.DisplayMember = "CompanyName";
}
}
}
the configuration class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace company1
{
class Configuration
{
string _CompanyName;
int _Employees;
int _Half;
public Configuration(string companyname, int number_of_Employees, int half)
{
_CompanyName = companyname;
_Employees = number_of_Employees;
_Half = half;
}
//program properties and validation
public string CompanyName
{
set
{
_CompanyName = value;
}
get
{
return _CompanyName;
}
}// End of levelname validation
//program properties and validation
public int EmployeesNumber
{
set
{
_Employees = value;
}
get
{
return _Employees;
}
}// End of levelname validation
//program properties and validation
public int Half
{
set
{
_Half = value;
}
get
{
return _Half;
}
}// End of levelname validation
}
}
any help appreciated, been trying for days to get it work.

// change the items in source list
var tmpLine = lines[10];
lines[10] = lines[9];
lines[9] = tmpLine;
// refresh datasource of listbox
listBox1.DataSource = null;
listBox1.DataSource = lines;

You could define an extension method for list to move items based on index:
public static class ExtensionClass
{
public static void Move<T>(this List<T> list, int index1, bool moveDown = true)
{
if (moveDown)
{
T temp = list[index1];
list[index1] = list[index1 + 1];
list[index1 + 1] = temp;
}
else
{
T temp = list[index1];
list[index1] = list[index1 - 1];
list[index1 - 1] = temp;
}
}
}
Then in Code you can:
List<int> list = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
Console.WriteLine("Original List");
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 2 Down");
list.Move(2);
foreach (int i in list)
{
Console.Write(i + ",");
}
Console.WriteLine(Environment.NewLine + "Move Index 3 Up");
list.Move(3, false);
foreach (int i in list)
{
Console.Write(i + ",");
}
Output will be:
Original List
1,2,3,4,5,6,7,
Move Index 2 Down
1,2,4,3,5,6,7,
Move Index 3 Up
1,2,3,4,5,6,7,

Related

C# duplicate component name

I have created a UserControl which has 2 properties.
See my code here:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.ComponentModel.Design;
namespace Controls
{
public partial class UserControl1: Panel
{
bool reset = false;
public bool _reset
{
get { return reset; }
set
{
reset = value;
if (value == true)
{
this.Controls.Clear();
cntCount = 0;
reset = false;
}
}
}
int cntCount = 0;
public int _cntCount
{
get { return cntCount; }
set
{
cntCount = value;
populate();
}
}
public UserControl1()
{
InitializeComponent();
}
void populate()
{
this.Controls.Clear();
IDesignerHost mDes = null;
mDes = (IDesignerHost)GetService(typeof(IDesignerHost));
for (int t = 0; t < cntCount; t++)
{
Button b = mDes.CreateComponent(typeof(Button), GenerateNewPaneName()) as Button;
this.Controls.Add(b);
}
}
protected string GenerateNewPaneName()
{
int curNum = 1;
bool bDuplicateName;
IReferenceService refsvc = GetService(typeof(IReferenceService)) as IReferenceService;
string curTry;
// Get a new component name
do
{
curTry = "b_" + curNum;
bDuplicateName = (refsvc.GetReference(curTry) != null);
curNum++;
}
while (bDuplicateName);
return curTry;
}
}
}
Dragging that control on the form is no problem.
If I enter a number into the property _cntCount, the control adds the required number of buttons inside my UserControl; no problem.
If I save the Form, close and reopen it, I get an error:
Duplicate component name 'b_1'. Component names must be unique and case-insensitive.
What do I miss?
Thanks in advance,
Murat

Sorting data from file in order from StreamReader

I have a windows form that uses a StreamReader to read form data into some text boxes. That works perfectly fine. The problem now is that I want to display the data from the file in order alphabetically by names. Early I tried an array.Sort method, by it didn't work so well.
Here is my code:
Note: I close the reader and file in the dispose method.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace ViewArchives
{
public partial class Form1 : Form
{
const char DELIM = ',';
const string FILENAME = #"F:\lscSpring2016\CIS2620\FinalProject\TicketMaster\bin\Debug\SoldTickets.txt";
string recordIn;
string[] fields;
static FileStream file = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(file);
public Form1()
{
InitializeComponent();
}
private void btnView_Click(object sender, EventArgs e)
{
try
{
recordIn = reader.ReadLine();
fields = recordIn.Split(DELIM);
nameBox.Text = fields[0];
ticketsBox.Text = fields[1];
purchaseBox.Text = fields[2];
dateBox.Text = fields[3];
}
catch (NullReferenceException)
{
label5.Text = "You have viewed\nall the records filed.";
btnView.Enabled = false;
}
}
}
}
There is a simpler way.
First, introduce a class for containing data from a single line:
class Record
{
public string Name { get; set; }
public string Tickets { get; set; }
public string Purchase { get; set; }
public string Date { get; set; }
}
In your Form1 class do the followings:
Create two fields.
One for the record list and one for indicating the current index in the record collection.
Record[] soldTickets; // This will contain the file data
int currentRecordIndex = -1;
Create a method that loads the whole file in one step into the record collection:
private void LoadRecords()
{
soldTickets =
File
.ReadAllLines(FILENAME)
.Select(line =>
{
string[] data = line.Split(DELIM);
return
new Record()
{
Name = data[0],
Tickets = data[1],
Purchase = data[2],
Date = data[3]
};
})
.OrderBy(record => record.Name)
.ToArray();
currentRecordIndex = -1;
}
Then your button click event handler can look like this:
private void btnView_Click(object sender, EventArgs e)
{
Record currentRecord = soldTickets.ElementAtOrDefault(++currentRecordIndex);
if (currentRecord == null)
{
label5.Text = "You have viewed\nall the records filed.";
btnView.Enabled = false;
return;
}
nameBox.Text = currentRecord.Name;
ticketsBox.Text = currentRecord.Tickets;
purchaseBox.Text = currentRecord.Purchase;
dateBox.Text = currentRecord.Date;
}

how to add to the list an object of class property in c sharp

I cannot add class instances correctly to a List. It adds only the last object. And when I debug the List vocabulary shows only adding the last class instance. So by second looping it has two entries of second object, by third looping it has three entries of third object. What I am doing wrong. Here is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace myVocabulary
{
public class Word
{
string _original_word;
string _translated_word;
public string Original_Word
{
get
{
return this._original_word;
}
set
{
this._original_word = value;
}
}
public string Translated_Word
{
get
{
return this._translated_word;
}
set
{
this._translated_word = value;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace myVocabulary
{
class Program
{
static List<Word> vocabulary = new List<Word>();
static void Main(string[] args)
{
Word entry = new Word();
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Enter word");
entry.Original_Word = Console.ReadLine();
Console.WriteLine("Enter Translation");
entry.Translated_Word = Console.ReadLine();
vocabulary.Add(entry);
}
}
}
}
Try this - You need to create a new Word object with each iteration of your loop, otherwise you're just overwriting the same instance repeatedly.
namespace myVocabulary
{
class Program
{
static List<Word> vocabulary = new List<Word>();
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
{
Word entry = new Word();
Console.WriteLine("Enter word");
entry.Original_Word = Console.ReadLine();
Console.WriteLine("Enter Translation");
entry.Translated_Word = Console.ReadLine();
vocabulary.Add(entry);
}
}
}
}

Solve recursion and infinite loop issue

I am currently writing a program which reads data in from a text file. The problem I am currently having is that the CompareTo method below is coming up with the error System.StackOverflowException was unhandled and saying "Make sure you don't have an infinite loop or infinite recursion. This error appears on the line return name.CompareTo(temp.name);.
The whole class is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Country
{
public class Country : IComparable
{
// Country Properties
private String name;
private float gdpGrowth;
private float inflation;
private float tradeBalance;
private float hdiRanking;
private LinkedList<String> tradePartners;
//Constructor
public Country(String name, float gdpGrowth, float inflation, float tradeBalance, float hdiRanking, LinkedList<String> tradePartners)
{
this.name = name;
this.gdpGrowth = gdpGrowth;
this.inflation = inflation;
this.tradeBalance = tradeBalance;
this.hdiRanking = hdiRanking;
this.tradePartners = tradePartners;
}
public String Name
{
set { this.name = value; }
get { return name; }
}
public float GdpGrowth
{
set { this.gdpGrowth = value; }
get { return gdpGrowth; }
}
public float Inflation
{
set { this.inflation = value; }
get { return inflation; }
}
public float TradeBalance
{
set { this.tradeBalance = value; }
get { return tradeBalance; }
}
public float HdiRankings
{
set { this.hdiRanking = value; }
get { return hdiRanking; }
}
public LinkedList<String> TradePartners
{
set { this.tradePartners = value; }
get { return tradePartners; }
}
public override string ToString()
{
return name + ", " + gdpGrowth + ", " + inflation + ", " + tradeBalance + ", " + hdiRanking + ", " + tradePartners;
}
public int CompareTo(object other)
{
Country temp = (Country)other;
return name.CompareTo(temp.name);
}
}
}
The class which is calling the country class is...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Country
{
public partial class Form1 : Form
{
private AVLTree<Country> countryTree = new AVLTree<Country>();
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// array to stroe each line of the file
String[] Lines = new string[1000];
String[] tempPartners = new string[1000];
int count = 0;
// Store each line of the file in the eachLine array
Lines = File.ReadAllLines("countries.csv");
foreach (String line in Lines)
{
if (count == 0)
{
count++;
}
else
{
// array to hold info
String[] info = new string[5];
//splits the countries
info = line.Split(',');
// split trade partners and puts in array
tempPartners = info[5].Split(';', '[', ']');
// insert current instance of country into AVL Tree
countryTree.InsertItem(new Country(info[0], float.Parse(info[1]),
float.Parse(info[2]), float.Parse(info[3]), float.Parse(info[4]), new LinkedList<String>(tempPartners)));
// create seperator
string seperator = ", ";
// stroe array
string partners = string.Join(seperator, tempPartners);
// remove first comma
partners = partners.Substring(1, partners.Length - 1);
//remove last comma
partners = partners.Remove(partners.Length - 2);
//pass in information from file into grid view
dataGridView1.Rows.Add(info[0], info[1], info[2], info[3], info[4], partners);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
You've got infinite recursion going here. CompareTo makes a recursive call but doesn't terminate due to the lack of a base case, so the recursive stack grows infinite. No actual comparison takes place either. What integer values do you want this to return, and under what conditions?
Perhaps as CyberDude said, you're really trying to use String.Compare(name, temp.name)?

Trying to read a text file into classes then cycle through

Hi am a fairly novice when it comes to c# and I have being trying to read out a text file then splitting it into sections with classes but have trouble with where to declare them an then how to cycle through the records. here's my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using System.Windows.Forms;
namespace Assignment_3
{
public partial class Form1 : Form
{
string s;
string ss;
int i = 1;
string infilename;
int num;
SortedList sList = new SortedList();
int x = 0;
public Form1()
{
InitializeComponent();
student myself = new student();
infilename = "text.txt";
StreamReader sr1 = new StreamReader(infilename);
sList.Clear();
while ((s = sr1.ReadLine()) != null)
{
string[] strs = s.Split(',');
myself.firstname = strs[0];
myself.middlename = strs[1];
myself.surname = strs[2];
myself.dob = DateTime.Parse(strs[3]);
myself.dob.ToString(strs[3]);
myself.sex = strs[4];
ss = myself.dob.ToString("u");
sList.Add(myself.firstname, myself);
}
sr1.Close();
num = sList.Count;
student[] pArray = new student[num];
string[] keys = new string[num];
foreach (DictionaryEntry d in sList)
{
keys[x] = (string)d.Key;
pArray[x] = (student)d.Value;
x++;
}
if (i == 0)
{lblmessage.Text = "Already at the first record."; i = 1; }
if (i == num)
{lblmessage.Text = "Already at the last record.";i = num-1; }
lbllastname.Text = pArray[i].surname;
lblfirstname.Text = pArray[i].firstname;
lblsecondname.Text = pArray[i].middlename;
lbldob.Text = pArray[i].dob.ToString();
lblsex.Text = pArray[i].sex;
}
private void btnlast_Click(object sender, EventArgs e)
{
i = num;
}
private void btnfirst_Click(object sender, EventArgs e)
{
i = 0;
}
private void btnnext_Click(object sender, EventArgs e)
{
i++;
}
private void btnprev_Click(object sender, EventArgs e)
{
i--;
}
}
}
and my class file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Assignment_3
{
class student
{
public string firstname;
public string middlename;
public string surname;
public DateTime dob;
public string sex;
}
}
anyone have any ideas where am going wrong?? I have no errors but find that the text fields do not update with the new record's and then when stepped through the array class holds the correct amount of records and fields, I feel its going to be something very obvious put cant put my finger on it.
Any help would be very appreciated.
You should create new instance of student inside for loop. Because at the moment you have only one instance of student class and all items in SortedList are pointing to same object.

Categories