CheckedListBox.SelectedItems.Count = 1? - c#

In C#, I have checked list boxes, that I need to store the data in arrays, but when I start the event that writes the objects to the array, I have to set the size of the array, which I naturally set to the amount of items checked. However, the items checked, for both checked list boxes I have is 1, no matter how many I check. Can someone help?
public partial class Form3 : Form
{
public static object[] dtype;
public static bool loaded = false;
bool typeselecte = false;
bool typeselectd = false;
public Form3()
{
InitializeComponent();
}
private void Form3_Shown(object sender, EventArgs e)
{
if (loaded)
{
int counte = 0;
int countd = 0;
types1.Items.AddRange(dtype);
types2.Items.AddRange(dtype);
if (typeselecte)
{
for (int i = 0; i < types1.Items.Count; i++)
{
if (i == Form1.enumber[counte])
{
types1.SelectedItems[i] = Form1.esearch[i];
counte++;
}
}
}
if (typeselectd)
{
for (int j = 0; j < types2.Items.Count; j++)
{
if (j == Form1.dnumber[countd])
{
types2.SelectedItems[j] = Form1.dsearch[j];
countd++;
}
}
}
}
}
public void dtypes()
{
dtype = new object[types1.Items.Count];
for (int i = 0; i < types1.Items.Count; i++)
{
dtype[i] = types1.Items[i];
}
}
private void button1_Click(object sender, EventArgs e)
{
if (types1.SelectedItems.Count > 0)
typeselecte = true;
if (types2.SelectedItems.Count > 0)
typeselectd = true;
Form1.esearch = new object[types1.SelectedItems.Count];
Form1.dsearch = new object[types2.SelectedItems.Count];
Form1.enumber = new int[types1.SelectedItems.Count];
Form1.dnumber = new int[types2.SelectedItems.Count];
int counte = 0;
int countd = 0;
if (typeselecte)
{
for (int i = 0; i < types1.SelectedItems.Count; i++)
Form1.esearch[i] = types1.SelectedItems[i];
}
if (typeselectd)
{
for (int j = 0; j < types2.SelectedItems.Count; j++)
Form1.dsearch[j] = types2.SelectedItems[j];
}
if (typeselecte)
{
for (int k = 0; k < types1.Items.Count; k++)
{
if (Form1.esearch[k] == types1.Items[k])
{
Form1.enumber[counte] = k;
counte++;
}
else
{
k--;
}
}
}
if (typeselectd)
{
for (int l = 0; l < types2.Items.Count; l++)
{
if (Form1.dsearch[l] == types2.Items[l])
{
Form1.dnumber[countd] = l;
countd++;
}
else
{
l--;
}
}
}
this.Close();
}
}
Form1.esearch and dsearch are object arrays, which the size hasn't been picked yet, and e and dnumber are int arrays that have unknown size as well, I just didn't feel the need to put in that code.

I believe you need to use the property CheckedItems as opposed to SelectedItems.

Related

Why I am not getting the last two entries from the CSV in my program?

Greetings fellow programmers, I need to ask you for a help.
I have this programm:
private void Import_CSV_Click(object sender, System.Windows.RoutedEventArgs e)
{
List<List<string>> x = new List<List<string>>();
try
{
List<string> row = new List<string>();
OpenFileDialog browseDialog = new OpenFileDialog();
browseDialog.Filter = "CSV Files (*.csv)|*.csv";
browseDialog.ShowDialog();
StreamReader sr = new StreamReader(browseDialog.FileName, Encoding.Default, true);
List<TOsoby> persons = new List<TOsoby>();
var file = sr.ReadToEnd();
var linesinthestream = file.Split(new char[] { '\n' });
for (int i = 0; i < linesinthestream.Count()-2; i++)
{
persons.Add(new TOsoby());
}
sr = new StreamReader(browseDialog.FileName, Encoding.Default, true);
string firstline = Akro.Helpers.String.RemoveDiacritics(sr.ReadLine().ToLower());
string[] values = firstline.Split(';');
for (int i = 0; i < values.Length; i++)
{
row.Add(values[i]);
}
x.Add(row);
while (!sr.EndOfStream)
{
row = new List<string>();
string lines = sr.ReadLine();
values = lines.Split(';');
for (int i = 0; i < values.Length; i++)
{
row.Add(values[i]);
}
x.Add(row);
}
for (int i = 0; i < x[0].Count-2; i++)
{
if (x[0][i] == "jmeno") //Tady je chyba J = 22. a count je 24 upakovaní neprojde.
{
for (int j = 0; j < x.Count-2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "name")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "firstname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Jmeno = x[j][i].ToString();
}
}
else if (x[0][i] == "prijmeni")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "surname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "lastname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "familyname")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Prijmeni = x[j][i].ToString();
}
}
else if (x[0][i] == "titul")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Titul = x[j][i].ToString();
}
}
else if (x[0][i] == "title")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Titul = x[j][i].ToString();
}
}
else if (x[0][i] == "email")
{
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].Email = x[j][i].ToString();
}
}
else if (x[0][i] == "")
{
return;
}
for (int j = 0; j < x.Count - 2; j++)
{
persons[j].OsobaID = 0;
}
}
if (persons == null) //Musím odstranit [0], protože tam je uložený první řádek a taky potřebujeme tam dát 23 řádků, takže nám tam 2 entry chybí (Marie a Michal), ale 22. řádek je uložen jako "", takže to musíme nějak opravit.
{
return;
}
else
{
persons.RemoveAt(0); //Tohle opravý ten první řádek
EntitiesModel em = DB.GetDB();
em.Add(persons); //23 a 24 tam vůbec nejsou (lidi z excelu)
em.SaveChanges();
Checker.CheckAfterEverySave();
}
}
catch (Exception er)
{
MessageBox.Show(er.Message);
}
}
My quest is to read the CSV entries and save them into the database, my problem is that last two entries of my CSV are not inside the persons, also on the last index it is empty:
Here is my CSV example I generated:
How should I fix it please?
Have a look at this, I included comments where I did changes to your code.
var csvFile = "A;B;C\nA 1;B 1;C 1\nA 2;B 2;C 2\nA 3;B 3;C 3\nA 4;B 4;C 4\n";
List<List<string>> x = new List<List<string>>();
List<Foo> foos = new List<Foo>();
//use StringSplitOptions.RemoveEmptyEntries to remove potential empty line at the end
var linesinthestream = csvFile.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < linesinthestream.Length - 1; i++) //-1 instead of - 2
foos.Add(new Foo());
List<string> row = new List<string>();
string firstline = linesinthestream[0];
string[] values = firstline.Split(';');
for (int i = 0; i < values.Length; i++)
row.Add(values[i]);
x.Add(row);
//use linesinthestream instead of again reading a stream start for loop at 1 and not 0 to skip the header
//you could remove the above code to read the header with this and start at 0, you don't really do anything different
for (int i = 1; i < linesinthestream.Length; i++)
{
row = new List<string>();
string lines = linesinthestream[i];
values = lines.Split(';');
for (int j = 0; j < values.Length; j++)
row.Add(values[j]);
x.Add(row);
}
//remove -2 to read all columns
for (int i = 0; i < x[0].Count; i++)
{
if (x[0][i] == "A")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderA = x[j][i].ToString();
}
else if (x[0][i] == "B")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderB = x[j][i].ToString();
}
else if (x[0][i] == "C")
{
//remove -2, start loop at 1, fill foo[j-1]
for (int j = 1; j < x.Count; j++)
foos[j-1].HeaderC = x[j][i].ToString();
}
}
//moved this loop outside of the previous loop, don't need to do it for every column
for (int j = 1; j < x.Count; j++)
foos[j-1].Id = 0;
foreach(var foo in foos)
Console.WriteLine($"Id: {foo.Id} | HeaderA: {foo.HeaderA} | HeaderB: {foo.HeaderB} | HeaderC: {foo.HeaderC}");
Find a demo here:
https://dotnetfiddle.net/tj0azu
As was already pointed out you should consider usign a library eg.
https://github.com/JoshClose/CsvHelper
and you can achieve the same result with this code:
using System;
using CsvHelper;
using CsvHelper.Configuration;
using System.Globalization;
using System.IO;
public class Program
{
public static void Main()
{
var csvFile = "A;B;C\nA 1;B 1;C 1\nA 2;B 2;C 2\nA 3;B 3;C 3\nA 4;B 4;C 4\n";
using (var reader = new StringReader(csvFile))
using (var csvReader = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture) { Delimiter = ";" }))
{
csvReader.Context.RegisterClassMap<FooMap>();
var foos = csvReader.GetRecords<Foo>();
foreach(var foo in foos)
Console.WriteLine($"Id: {foo.Id} | HeaderA: {foo.HeaderA} | HeaderB: {foo.HeaderB} | HeaderC: {foo.HeaderC}");
}
}
}
public class Foo
{
public int Id {get;set;}
public string HeaderA {get;set;}
public string HeaderB {get;set;}
public string HeaderC {get;set;}
}
public sealed class FooMap : ClassMap<Foo>
{
public FooMap()
{
AutoMap(CultureInfo.InvariantCulture);
Map(m => m.Id).Ignore();
Map(m => m.HeaderA).Name("A");
Map(m => m.HeaderB).Name("B");
Map(m => m.HeaderC).Name("C");
}
}
Find a demo here:
https://dotnetfiddle.net/1jaYNw
I recommend using FileHelpers. There is a nuget package available. I have used this for parsing several CSV files with no issue.
Here is some example code that will read a CSV file through a Stream and create a List<T> of the class that is provided:
using FileHelpers;
using System;
using System.Collections.Generic;
using System.IO;
public class DataFileConverter<T> : IDisposable where T : class
{
private readonly IFileHelperAsyncEngine<T> _engine;
private bool _disposed = false;
public DataFileConverter()
{
_engine = new FileHelperAsyncEngine<T>();
}
~DataFileConverter()
{
Dispose(false);
}
public bool RemoveHeaderRow
{
get => _engine.Options.IgnoreFirstLines == 1;
set => _engine.Options.IgnoreFirstLines = value ? 1 : 0;
}
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
if (_engine != null)
{
_engine.Close();
}
}
_disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public List<T> ReadDataFile(Stream stream)
{
List<T> data = new List<T>();
using var streamReader = new StreamReader(stream);
using (_engine.BeginReadStream(streamReader))
{
foreach (T datum in _engine)
{
data.Add(datum);
}
}
return data;
}
}
using FileHelpers;
using System;
[DelimitedRecord(",")]
public class SomeClass
{
[FieldCaption("column1")]
public string SomeProperty1 { get; set; }
[FieldCaption("column2")]
[FieldConverter(ConverterKind.Date, "yyyy-MM-dd")]
public DateTime SomeProperty2 { get; set; }
}
public class SomeService
{
using DataFileConverter<SomeClass> converter = new DataFileConverter<SomeClass>
{
RemoveHeaderRow = true
};
List<SomeClass> data = converter.ReadDataFile(System.IO.File.OpenRead("path/to/file"));
// do whatever logic with data
}

How to eliminate repeating code in Sorting methods -C#

Please, help me to eliminate repeating code in "SortMG" and "SortByName" methods. It is basically the same text and it annoys me.
class Student
{
public string name;
public string major;
public double grade;
public string studyForm;
public Student(string name, string major, double grade, string studyForm)
{
this.name = name;
this.major = major;
this.grade = grade;
this.studyForm = studyForm;
}
}
class Program
{
static void SortMG(Student[] sortMG, int n)
{
int i, j;
Student tmpMG = new Student("","", 0, "");
for (i = 0; i < n - 1; i++)
{
for (j = i; j < n; j++)
{
if (sortMG[j].major.CompareTo(sortMG[i].major)<0)
{
//I'm asking about this part:
tmpMG.name = sortMG[j].name;
tmpMG.major = sortMG[j].major;
tmpMG.studyForm = sortMG[j].studyForm;
tmpMG.grade = sortMG[j].grade;
sortMG[j].name = sortMG[i].name;
sortMG[j].major = sortMG[i].major;
sortMG[j].studyForm = sortMG[i].studyForm;
sortMG[j].grade = sortMG[i].grade;
sortMG[i].name = tmpMG.name;
sortMG[i].major = tmpMG.major;
sortMG[i].studyForm = tmpMG.studyForm;
sortMG[i].grade = tmpMG.grade;
}
else if (sortMG[j].major.CompareTo(sortMG[i].major) == 0)
{
if (sortMG[j].grade > sortMG[i].grade)
{
//and this part:
tmpMG.name = sortMG[j].name;
tmpMG.major = sortMG[j].major;
tmpMG.studyForm = sortMG[j].studyForm;
tmpMG.grade = sortMG[j].grade;
sortMG[j].name = sortMG[i].name;
sortMG[j].major = sortMG[i].major;
sortMG[j].studyForm = sortMG[i].studyForm;
sortMG[j].grade = sortMG[i].grade;
sortMG[i].name = tmpMG.name;
sortMG[i].major = tmpMG.major;
sortMG[i].studyForm = tmpMG.studyForm;
sortMG[i].grade = tmpMG.grade;
}
}
}
}
}
static void SortByName(Student[] sortN, int n)
{
int i, j;
Student tmpN = new Student("", "", 0, "");
for (i = 0; i < n - 1; i++)
{
for (j = i; j < n; j++)
{
if (sortN[j].name.CompareTo(sortN[i].name) < 0)
{
//and this part:
tmpN.name = sortN[j].name;
tmpN.major = sortN[j].major;
tmpN.studyForm = sortN[j].studyForm;
tmpN.grade = sortN[j].grade;
sortN[j].name = sortN[i].name;
sortN[j].major = sortN[i].major;
sortN[j].studyForm = sortN[i].studyForm;
sortN[j].grade = sortN[i].grade;
sortN[i].name = tmpN.name;
sortN[i].major = tmpN.major;
sortN[i].studyForm = tmpN.studyForm;
sortN[i].grade = tmpN.grade;
}
}
}
}
}
It looks like you are "swapping" items by swapping their property values. Seems like you should be just swapping the items instead:
if (sortMG[j].grade > sortMG[i].grade)
{
//and this part:
tmpMG = sortMG[j];
sortMG[j] = sortMG[i];
sortMG[i] = tmpMG;
}
You could also move that swap into a function that you call from the three locations to reduce duplicate code further:
public void Swap(Student[] sortMG, int i, int j)
{
//TODO: add bounds/null hecking
var tmpMG = sortMG[j];
sortMG[j] = sortMG[i];
sortMG[i] = tmpMG;
}
You could save yourself a lot of work by using Linq.
For example you could sort a Student[] by Major with the following:
List<Student> students = new List<Student>()
{
new Student("Jose Mendez", "Math", 80, "Beta"),
new Student("Alex Bello", "Math", 90, "Alpha"),
new Student("Bob Junior", "EE", 100, "Charlie")
};
Student[] array = students.ToArray();
array = array.OrderBy(x => x.Major).ToArray();
It seems like you are asking for something like:
static void copyStudent(Student from, Student to)
{
Student tmpMG = new Student();
tmpMG.name = from.name;
tmpMG.major = from.major;
tmpMG.studyForm = from.studyForm;
tmpMG.grade = from.grade;
from.name = to.name;
from.major = to.major;
from.studyForm = to.studyForm;
from.grade = to.grade;
to.name = tmpMG.name;
to.major = tmpMG.major;
to.studyForm = tmpMG.studyForm;
to.grade = tmpMG.grade;
}
static void SortMG(Student[] sortMG, int n)
{
int i, j;
for (i = 0; i < n - 1; i++)
{
for (j = i; j < n; j++)
{
if (sortMG[j].major.CompareTo(sortMG[i].major)<0)
copyStudent(sortMG[j], sortMG[i]);
else if (sortMG[j].major.CompareTo(sortMG[i].major) == 0)
{
if (sortMG[j].grade > sortMG[i].grade)
copyStudent(sortMG[j], sortMG[i]);
}
}
}
}
static void SortByName(Student[] sortN, int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = i; j < n; j++)
if (sortN[j].name.CompareTo(sortN[i].name) < 0)
copyStudent(sortN[j], sortN[i]);
}
why not use:
static void SortMG(Student[] sortMG, int n)
{
sortMG = sortMG.OrderBy(i => i.major).ThenBy(i=> i.grade).ToArray();
}
static void SortByName(Student[] sortN, int n)
{
sortN = sortN.OrderBy(i => i.name).ToArray();
}

Resizing controls to maintain original proportion size Winforms C#

I'm trying to resize my control and maintain they're current position. I've tried doing it by keeping the original proportion in list and comparing it and resizing it accordingly whenever the size of the form is changed.
The result http://prntscr.com/bc796l -> http://prntscr.com/bc79a2
Can you guide me where my problem is or suggest a different approach
private void Form_Resize(object sender, EventArgs e)
{
Control.ControlCollection controls = Controls;
List<Size> newSizes = new List<Size>();
for (int j = 0; j < controls.Count; j++)
{
int widthProportion = Bounds.Width / controls[j].Width;
int heightProportion = Bounds.Height/controls[j].Height;
string controlName = controlProportions[j].Item1;
int originalWidthProportion = controlProportions[j].Item2;
int originalHeightProportion = controlProportions[j].Item3;
if (controls[j].Name == controlName)
{
if (widthProportion > originalWidthProportion)
{
while (widthProportion > originalWidthProportion)
{
originalWidthProportion++;
}
}
else if (widthProportion < originalWidthProportion)
{
while (widthProportion < originalWidthProportion)
{
originalWidthProportion--;
}
}
if (heightProportion > originalHeightProportion)
{
while (heightProportion > originalHeightProportion)
{
originalHeightProportion++;
}
}
else if (heightProportion < originalHeightProportion)
{
while (heightProportion < originalHeightProportion)
{
originalHeightProportion--;
}
}
newSizes.Add(new Size(Bounds.Width/originalWidthProportion, Bounds.Height/originalHeightProportion));
controlProportions[j] = new Tuple<string, int, int>(controls[j].Name, originalWidthProportion,
originalHeightProportion);
}
}
for (int j = 0; j < controls.Count; j++)
{
controls[j].Size = newSizes[i];
}
}
That's how I originally populate the list :
private static readonly List<Tuple<string,int, int>> controlProportions = new List<Tuple<string,int, int>>();
private void SetControlProportions()
{
Control.ControlCollection controls = Controls;
foreach (Control control in controls)
{
int heightProportion = Bounds.Height / control.Height;
int widthProportion = Bounds.Width / control.Width;
controlProportions.Add(new Tuple<string, int, int>(control.Name,widthProportion, heightProportion));
}
}

How to search and replace words in a WPF TextBox?

I've found several examples that do this but with richTextBox instead. Is it even possible to replace words in a multi-line TextBox?
you can do this for searchin' the next word automatically in textbox
int t = 0;
private void FindNext(object sender, RoutedEventArgs e)
{
for (int i = t; i < NoteText.Text.Length-SearchBar.Text.Length; i++)
{
string x = "";
for (int j = 0; j < SearchBar.Text.Length; j++)
{
if(SearchBar.Text[j] == NoteText.Text[i+j])
{
x += NoteText.Text[i + j] + "";
}
else
{
x = "";
}
}
if(x == SearchBar.Text)
{
t = i+1;
NoteText.Focus();
NoteText.SelectAll();
NoteText.Select(i, SearchBar.Text.Length);
break;
}
if(i==NoteText.Text.Length - SearchBar.Text.Length - 1)
{
MessageBox.Show("The search was completed");
t = 0;
}
s = t;
}
}

File upload in ASP.NET and C#

i needed a file upload feature in my project built on ASP.NET 3.5 and C#. I followed the following link to do so.
http://support.microsoft.com/kb/323246.
I created a folder named Data and followed everything as stated in the link.But my files didnt get uploaded in that folder named Data.What should i do to upload a file?
Any exception is thrown? Do you give the permission to the account you program run under? What's size of your file upload? Try a small one first, such as 1K file. ASP.NET has a size limit, and you can change the limit in the config file.
class Proizvod {
public string ceo_red, ime, proizvodjac, ram, tip, kamera,slika, ekran,sifra, cena;
public Proizvod(string x) {
ceo_red = x;
slika = x.Split(',')[0];
sifra = x.Split(',')[1];
ime = x.Split(',')[2];
proizvodjac = x.Split(',')[3];
ram = x.Split(',')[4];
tip = x.Split(',')[5];
kamera = x.Split(',')[6];
ekran = x.Split(',')[7];
cena = x.Split(',')[8];
}
}
List<Proizvod> proizvodi = new List<Proizvod>();
protected void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(#"F:\dji\A8\A8\TextFile1.txt");
for (int i = 0; i < 5; i++)
{
proizvodi.Add(new Proizvod(sr.ReadLine()));
}
for (int i = 0; i < proizvodi.Count; i++)
{
bool isti = false;
for (int j = 0; j < DropDownList1.Items.Count; j++)
{
if (proizvodi[i].proizvodjac == DropDownList1.Items[j].Text) isti = true;
}
if (!isti) DropDownList1.Items.Add(proizvodi[i].proizvodjac);
isti = false;
for (int j = 0; j < DropDownList2.Items.Count; j++)
{
if (proizvodi[i].ram == DropDownList2.Items[j].Text) isti = true;
}
if (!isti) DropDownList2.Items.Add(proizvodi[i].ram);
isti = false;
for (int j = 0; j < DropDownList3.Items.Count; j++)
{
if (proizvodi[i].tip == DropDownList3.Items[j].Text) isti = true;
}
if (!isti) DropDownList3.Items.Add(proizvodi[i].tip);
isti = false;
for (int j = 0; j < DropDownList4.Items.Count; j++)
{
if (proizvodi[i].kamera == DropDownList4.Items[j].Text) isti = true;
}
if (!isti) DropDownList4.Items.Add(proizvodi[i].kamera);
isti = false;
for (int j = 0; j < DropDownList5.Items.Count; j++)
{
if (proizvodi[i].ekran == DropDownList5.Items[j].Text) isti = true;
}
if (!isti) DropDownList5.Items.Add(proizvodi[i].ekran);
}
Table1.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
List<Proizvod> trazeni = new List<Proizvod>();
for (int i = 0; i < proizvodi.Count; i++)
{
if (proizvodi[i].proizvodjac == DropDownList1.Text && proizvodi[i].ram == DropDownList2.Text && proizvodi[i].tip == DropDownList3.Text && proizvodi[i].kamera == DropDownList4.Text && proizvodi[i].ekran == DropDownList5.Text)
{
trazeni.Add(proizvodi[i]);
}
}
for (int i = 0; i < trazeni.Count; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < 9; j++)
{
TableCell tc = new TableCell();
tc.Text = trazeni[i].ceo_red.Split(',')[j];
tr.Cells.Add(tc);
}
Table1.Rows.Add(tr);
}
Table1.Visible = true;
}
}
}

Categories