C# WPF Read/Edit CSV - c#

I am currently writing an application in WPF C# that is some kind of helper for other processes which are written in Java. Those other processes require a configuration.csv in which different "names" are listed with a column that says "SKIP". If the column is X at Skip, my java program will skip those names and therefore their dependent processes.
If I open the CSV with Excel and edit the rows, everything works perfectly fine. That's not the problem. What I want to achieve is to list the rows into a DataGrid in a WPF App (except the first and last row), where the user can tick a checkbox to decide if he wants to skip that specific name or not. By pressing Save, the .CSV gets updated.
I already wrote some code with a friend who's more familiar with this topic. It worked fine in WinForms but doesn't work on WPF. We are not able to get the values of the checkboxes and not able to save them into the CSV.
CODE:
private void OBJ_SaveButton_Click(object sender, RoutedEventArgs e)
{
if (OBJ_DataGrid.Items.Count == 0)
{
MessageBox.Show("Kein Datensatz in der View.");
return;
}
/*if (Directory.Exists(path))
{
if (File.Exists(filepath))
{
string tmp = null;
try
{
FileStream fileStr = new FileStream(filepath, FileMode.Create);
StreamWriter strWriter = new StreamWriter(fileStr);
strWriter.WriteLine("SFObject;Skip");
for(int i=0;i< itmGrd.Count;i++)
{
switch (itmGrd[i].ItemValue)
{
case true:
tmp = itmGrd[i].ItemName + ";X";
break;
case false:
tmp = itmGrd[i].ItemName + ";";
break;
}
strWriter.WriteLine(tmp);
}
strWriter.WriteLine("SuccessMSG;");
strWriter.Close();
fileStr.Close();
LoadConf();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
MessageBox.Show("ERR_F0: Pfad nicht gefunden.");
}
else
MessageBox.Show("ERR_D0: Pfad nicht gefunden.");*/
}
private void OBJ_ReloadButton_Click(object sender, RoutedEventArgs e)
{
}
private void OBJ_DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void OBJ_DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
MessageBox.Show(e.Row.ToString());
}
void OnChecked(object sender, RoutedEventArgs e)
{
MessageBox.Show(e.Source.ToString());
}
}
public class ItemGrid
{
public ItemGrid(string name, bool rval)
{
ItemName = name;
ItemValue = rval;
}
public string ItemName { set; get; }
public bool ItemValue { set; get; }
}
public class ItemsGrid : List<ItemGrid>
{
public string path = null;
public string filepath = null;
public ItemsGrid()
{
path = String.Format(#"{0}\build\", Environment.CurrentDirectory);
filepath = Path.Combine(path + "configuration.csv");
if (Directory.Exists(path))
{
if (File.Exists(filepath))
{
string line = null;
StreamReader file = new StreamReader(filepath);
while ((line = file.ReadLine()) != null)
{
if (!line.Equals("SFObject;Skip") && !line.Equals("SuccessMSG;"))
{
string input = (line.IndexOf(";X") != -1 ? (line.Replace(";X", "")) : (line.Replace(";", "")));
Add(new ItemGrid(input, (line.IndexOf(";X") != -1 ? (true) : (false))));
}
}
file.Close();
}
else
MessageBox.Show("ERR_F0: Pfad nicht gefunden.");
}
else
MessageBox.Show("ERR_D0: Pfad nicht gefunden.");
//Add(new ItemGrid("Tom", false));
// Add(new ItemGrid("Jen", false));
}
}
This is how it looks (and should look like).
CSV:
I hope that you guys can help me out, I really don't understand why it's not working. I also have to admit that I am not any near of being proficient in C#.

I'm assuming the CSV you pasted is considered properly formatted.
// HelperClass.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfCsvSkipTicker
{
public static class HelperClass
{
public static List<ItemGrid> ReadCsv(string filepath)
{
if (!File.Exists(filepath)) return null;
var allLines = File.ReadAllLines(filepath);
var result =
from line in allLines.Skip(1).Take(allLines.Length -2)
let temparry = line.Split(';')
let isSkip =
temparry.Length > 1
&& temparry[1] != null
&& temparry[1] == "X"
select new ItemGrid { ItemName = temparry[0], ItemValue = !isSkip };
return result.ToList();
}
public static void WriteCsv(IEnumerable<ItemGrid> items, string filepath)
{
var temparray = items.Select(item => item.ItemName + ";" + (item.ItemValue ? "" : "X")).ToArray();
var contents = new string[temparray.Length + 2];
Array.Copy(temparray, 0, contents, 1, temparray.Length);
contents[0] = "SFOBject;Skip";
contents[contents.Length - 1] = "SuccessMSG;";
File.WriteAllLines(filepath, contents);
}
}
public class ItemGrid
{
public string ItemName { set; get; }
public bool ItemValue { set; get; }
}
}
And...
// MainWindow.xaml.cs
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.dataGridView.ItemsSource = HelperClass.ReadCsv(#"PathToRead\configuration.csv");
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
var temp = new List<ItemGrid>();
for (int i = 0; i < this.dataGridView.Items.Count; i++)
{
if (this.dataGridView.Items[i] is ItemGrid) // DataGrid pads it's item collection with elements we didn't add.
temp.Add((ItemGrid)this.dataGridView.Items[i]);
}
HelperClass.WriteCsv(temp, #"PathToSave\new_configuration.csv");
}
}

Related

Music Player in C# Does Tot Play The Song I Added Later

I made an mp3 player in C#. If I select the songs at once, they automatically play one after the other, but when it comes to a song I added later, I get a "System.IndexOutOfRangeException" error. When I add music later, I want the song to play automatically one after the other, how can I do that?
string[] yol, dosya;
private void Btn_Muzik_Ekle_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
if (ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
dosya = ofd.SafeFileNames;
yol = ofd.FileNames;
for (int x = 0; x < dosya.Length; x++)
{
Lb_Muzik_Listesi.Items.Add(dosya[x]);
}
}
}
private void Lb_Muzik_Listesi_SelectedIndexChanged(object sender, EventArgs e)
{
//This Is Where I Got The Error
OynatmaEkranı.URL = yol[Lb_Muzik_Listesi.SelectedIndex];
OynatmaEkranı.Ctlcontrols.play();
try
{
var file = TagLib.File.Create(yol[Lb_Muzik_Listesi.SelectedIndex]);
var bin = (byte[])(file.Tag.Pictures[0].Data.Data);
Pb_Muzik_Kapak.Image = Image.FromStream(new MemoryStream(bin));
}
catch
{
}
}
private void Zamanlayıcı_Tick(object sender, EventArgs e) //Timer
{
if (OynatmaEkranı.playState==WMPLib.WMPPlayState.wmppsPlaying)
{
Pb_Muzik.Maximum=(int)OynatmaEkranı.Ctlcontrols.currentItem.duration;
Pb_Muzik.Value = (int)OynatmaEkranı.Ctlcontrols.currentPosition;
try
{
Lbl_Muzik_Sure.Text = OynatmaEkranı.Ctlcontrols.currentPositionString;
Lbl_Muzik_Bitis.Text = OynatmaEkranı.Ctlcontrols.currentItem
.durationString.ToString();
}
catch
{
}
}
if (Pb_Muzik.Value==Pb_Muzik.Maximum)
{
if (Lb_Muzik_Listesi.SelectedIndex<Lb_Muzik_Listesi.Items.Count-1)
{
Lb_Muzik_Listesi.SelectedIndex = Lb_Muzik_Listesi.SelectedIndex + 1;
}
}
}
You can avoid this problem managing your data in the ListBox. Create a class with your required info (the file and the name):
public class MuzikItem
{
public MuzikItem(string file)
{
this.Text = System.IO.Path.GetFileNameWithoutExtension(file);
this.Url = file;
}
public string Text { get; set; }
public string Url { get; set; }
public override string ToString()
{
// This is the text to show in ListBox
return this.Text;
}
}
Add items to the ListBox using this class:
foreach (var file in ofd.FileNames)
{
var item = new MuzikItem(file);
Lb_Muzik_Listesi.Items.Add(item);
}
And use it:
var item = Lb_Muzik_Listesi.SelectedItem as MuzikItem;
if (item != null)
{
OynatmaEkranı.URL = item.Url;
OynatmaEkranı.Ctlcontrols.play();
try
{
var file = TagLib.File.Create(item.Url);
var bin = (byte[])file.Tag.Pictures[0].Data.Data;
Pb_Muzik_Kapak.Image = Image.FromStream(new MemoryStream(bin));
}
catch
{
}
}
You try to get the selected item as a MuzikItem (all your items are of this class so this return null only when no item is selected) and with this, you have the Url.
UPDATE
I like manage this things with events. In your Ticks methods:
if (Pb_Muzik.Value == Pb_Muzik.Maximum)
{
OnSongFinished();
}
And create a method to manage this event:
private void OnSongFinished()
{
if (Lb_Muzik_Listesi.SelectedIndex < Lb_Muzik_Listesi.Items.Count - 1)
{
Lb_Muzik_Listesi.SelectedIndex = Lb_Muzik_Listesi.SelectedIndex + 1;
}
else
{
// Stop the player
OynatmaEkrani.Ctlcontrols.stop();
}
}

WPF Set attributes back after a event is finished

so what i would like to is setting back some attributes after an Custom Event is finished.
Scenario i have a save BackupDrives Class that does collection of data and then offers a Event to be called after its done.
Changing object properties can be done by button click, what i would like is to set them back to the same value after the event is finished.
Button click does the thing :
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.SaveDrives += OnSavingDrives;
backup.DrivesSave();
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
Now the triggered event method is not able to change the properties back.
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(....);
File.WriteAllLines(e.Something, e.List2ToSave);
File.WriteAllLines(e.Something_lse, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
How do i do this. Since this does not work.
And on other thig here to - when i run the GUI i need to click 2 times one the same button to start it all. Done Code Clean + Rebuild. Still the same.
---EDIT---
As for code here you go.
This is a Class for collecting method and event.
public class DrivesEventArgs : EventArgs
{
string MYDOC = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
const string backup_Drives = "....";
const string backup_Letters = "...";
public List<string> List1ToSave = new List<string>();
public List<string> List2ToSave = new List<string>();
public string SAVE_DRIVE_Letter
{
get
{
string name = Path.Combine(MYDOC, backup_Letters);
return name;
}
}
public string SAVE_DRIVE_Path
{
get
{
string name = Path.Combine(MYDOC, backup_Drives);
return name;
}
}
}
public class DrivesBackup
{
private const string path = "Network";
private List<string> drives_to_save = new List<string>();
private List<string> letters_for_drives = new List<string>();
private RegistryKey reg1, reg2;
public event EventHandler<DrivesEventArgs> SaveDrives;
public void DrivesSave()
{
var data = new DrivesEventArgs();
try
{
if (drives_to_save.Count == 0)
{
reg1 = Registry.CurrentUser.OpenSubKey(path);
string[] mounted_drives = reg1.GetSubKeyNames();
foreach (var drive in mounted_drives)
{ //get all UNC Paths from mounted_drives
string[] getUNC = { path, drive };
string fullUNC = Path.Combine(getUNC);
reg2 = Registry.CurrentUser.OpenSubKey(fullUNC);
string UNCPath = reg2.GetValue("RemotePath").ToString(); //getting UNC PATH
Console.WriteLine(UNCPath);
data.List1ToSave.Add(drive.ToString());
data.List2ToSave.Add(UNCPath);
OnSaveDrives(data);
}
}
}
catch (Exception er)
{
throw er;
}
}
protected virtual void OnSaveDrives(DrivesEventArgs eD)
{
SaveDrives?.Invoke(this, eD);
}
Now here is the MAINWINDOW WPF
public partial class MainWindow : Window
{
DrivesBackup backup = new DrivesBackup();
public MainWindow()
{
InitializeComponent();
}
private void bbdrives_Click(object sender, RoutedEventArgs e)
{
backup.DrivesSave();
backup.SaveDrives += OnSavingDrives;
Drive_text.Visibility = Visibility.Visible;
drives_progres.Visibility = Visibility.Visible;
drives_progres.IsIndeterminate = true;
}
private void OnSavingDrives(object sender, DrivesEventArgs e)
{
Directory.CreateDirectory(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"SEG-Backup"));
File.WriteAllLines(e.SAVE_DRIVE_Path, e.List2ToSave);
File.WriteAllLines(e.SAVE_DRIVE_Letter, e.List1ToSave);
Drive_text.Visibility = Visibility.Collapsed;
drives_progres.Visibility = Visibility.Collapsed;
drives_progres.IsIndeterminate = false;
}
}
Now i do hope this would make some things more clear.

Method not passing result back to main program

Having some real trouble understanding where I've gone wrong here. I've marked in the code what and where. I am using an XAML interface and do have objects for everything here. The code compiles but the TextBlock will not update with the result from updateVTCShortCode Thanks for the help!
MAIN PROGRAM
namespace VTCPT
{
/// <summary>
///
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
public void shortFormCodec_SelectionChanged(object sender, RoutedEventArgs e)
{
//UPDATE THE SHORTCODE TEXTBLOCK
updateVTCShortCode display = new updateVTCShortCode();
display.mergeShortCode(longFormCodec.SelectedItem.ToString());
if (String.IsNullOrEmpty(display.finalResult()))
{ shortFormCodec.Text = ".."; }
else { shortFormCodec.Text = display.finalResult();
shortFormCodec.Text = "test";
} /////THIS IS NOT ACTUALLY GETTING A RETURN
}
public void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void updateShortForm(object sender, SelectionChangedEventArgs e)
{
}
private void TextBlock_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void fsSiteBuild_SelectionChanged(object sender, RoutedEventArgs e)
{
}
private void updateSiteBuild(object sender, TextChangedEventArgs e)
{
int index = fsRoomDesig.Text.IndexOf(".");
if (index > 0)
{ fsSiteBuild.Text = fsRoomDesig.Text.Substring(0, index); }
else { fsSiteBuild.Text = ".."; }
}
private void vtcSystemName_SelectionChanged(object sender, RoutedEventArgs e)
{
}
}
}
updateVTCShortCode CLASS
namespace VTCPT
{
class updateVTCShortCode
{
String result = "";
public void mergeShortCode(String longFormCodec)
{ if (longFormCodec.Equals("Cisco SX80"))
{
String sendShortForm = "SX80";
result = "V-T" + sendShortForm;
}
if (longFormCodec.Equals("Cisco Webex Codec Plus"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
if (longFormCodec.Equals("Cisco Webex Codec Pro"))
{
String sendShortForm = "SRK";
result = "V-T" + sendShortForm;
}
}
public String finalResult()
{ return result; } //////SHOULD BE GETTING SENT BACK TO MAIN PROGRAM
}
}
I think the problem is that in the following code taken from your shortFormCodec_SelectionChanged method. You set shortFormCodec.Text = display.finalResult(); immediately followed by shortFormCodec.Text = "test";. The final result will never be visible because it is being immediately overwritten with "test".
if (String.IsNullOrEmpty(display.finalResult()))
{
shortFormCodec.Text = "..";
}
else
{
shortFormCodec.Text = display.finalResult();
shortFormCodec.Text = "test";
}
As TheGeneral suggested in the comments, you should be able to identify this using breakpoints and stepping through the code (using the F8 key) while watching the values of your variables and text fields. If you hover your mouse over the variables and the .Text section of any shortFormCodec.Text line it will show you its value at that point in the program.
However, I think you may find it helpful if you adjust your code to use an if {} else if {} else {} structure. I would also change the finalResult() method to a property as it's doing nothing but return a string. For example:
class updateVTCShortCode
{
// You could set the default value to an empty string I.e. = ""
// but having it set to "Not set" may help you spot any problems for now.
// As long as you remember to call mergeShortCode() first, you would never
// see "Not set" returned anyway. But this would help you spot that mistake.
public string FinalResult { get; set; } = "Not set";
public void mergeShortCode(String longFormCodec)
{
if (longFormCodec.Equals("Cisco SX80"))
{
String sendShortForm = "SX80";
FinalResult = "V-T" + sendShortForm;
}
else if (longFormCodec.Equals("Cisco Webex Codec Plus"))
{
String sendShortForm = "SRK";
FinalResult = "V-T" + sendShortForm;
}
else if (longFormCodec.Equals("Cisco Webex Codec Pro"))
{
String sendShortForm = "SRK";
FinalResult = "V-T" + sendShortForm;
} else
{
// If longFormCodec is not matched, set the result to ".."
FinalResult = "..";
}
}
By setting the final result to ".." in the else block of the mergeShortCode() method and setting a default value for the FinalResult property (even if it is an empty string I.e. ""). You are preventing FinalResult ever being null and providing all possible outcomes from the one function. This means you can simplify the shortFormCodec_SelectionChanged() method to the following and easily reuse the mergeShortCode() method elsewhere:
public void shortFormCodec_SelectionChanged(object sender, RoutedEventArgs e)
{
//UPDATE THE SHORTCODE TEXTBLOCK
updateVTCShortCode display = new updateVTCShortCode();
display.mergeShortCode(longFormCodec.SelectedItem.ToString());
shortFormCodec.Text = display.FinalResult;
}
}

Access list in class from another class

I know this is asked before, but I can't seem to figure it out.
I have a class which makes a list from a datagridview. I want to do stuff with this list in another class but I cant't access it. I can access it from Form1.cs like the code underneath. How do I access the list from a random class like I can in Form1.cs?
//Opens the file dialog and assigns file path to Textbox
OpenFileDialog browseButton = new OpenFileDialog();
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
ExcelPath.Text = browseButton.FileName;
fileExcel = ExcelPath.Text;
//SetAttributeValue(ExcelPath, fileExcel);
//nylp();
/*
////IMPORTERER 10TAB-DATA FRA EXCEL TIL DATAGRIDVIEW////
tenTabLine.fileExcel = fileExcel;
tenTabLine.tenTab(tenTabDgv);
*/
////IMPORTERER NYLPDATA TIL DATAGRIDVIEW////
nylpLine.fileExcel = fileExcel;
nylpLine.nylpData(nylpDgv);
////TAR DATA I NYLPDGV DATAGRIDVIEW OG BEREGNER VERTIKALE ELEMENTER////
vertElementer.vertBueDGV(nylpDgv, vertElementerDgv);
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
else return;
}
When I try to do something like this I get lot of errors in Error List:
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
This is my list class
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i<VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
public class vertEl
{
private int _elNr;
private double _p1;
private double _p2;
private double _z1;
private double _z2;
private double _nylpRad;
private double _heln1;
private double _heln2;
public int elNr
{
get { return _elNr; }
set { _elNr = value; }
}
public double p1
{
get { return _p1; }
set { _p1 = value; }
}
public double p2
{
get { return _p2; }
set { _p2 = value; }
}
public double z1
{
get { return _z1; }
set { _z1 = value; }
}
public double z2
{
get { return _z2; }
set { _z2 = value; }
}
public double nylpRad
{
get { return _nylpRad; }
set { _nylpRad = value; }
}
public double heln1
{
get { return _heln1; }
set { _heln1 = value; }
}
public double heln2
{
get { return _heln2; }
set { _heln2 = value; }
}
}
EDIT:
I've made it work now except that I get a out of range exception.
class code is:
class GetKoord
{
public GetVertElementasList getList = new GetVertElementasList();
BridgGeometry obj = new BridgGeometry();
public void foo()
{
var TEST = getList.vertList(obj.vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
}
In form1 or BridgGeometry as it is called in my project I have which is giving me out of range exception.
GetKoord getZ = new GetKoord();
getZ.foo();
EDIT2:
The code underneath works and gives a message box with some value in list. But the method foo() in class above gives a out of range error.
private void browse_Click(object sender, EventArgs e)
{
browseButton.Filter = "Excel Files |*.xlsx;*.xls;*.xlsm;*.csv";
if (browseButton.ShowDialog() == DialogResult.OK)
{
////TESTING////WORKING CODE AND GIVES A MESSAGEBOX WITH VALUE
GetVertElementasList getVertList = new GetVertElementasList();
var TEST = getVertList.vertList(vertElementerDgv);
MessageBox.Show(TEST[2].elNr.ToString());
}
else return;
}
I think you are trying to access the variable directly in the class; which will not work. Try following
class GetKoord
{
GetVertElementasList getList = new GetVertElementasList();
public void foo()
{
var TEST = getList.vertList(vertElementerDgv);
MessageBox.Show(TEST[5].p2.ToString());
}
}
I tested your code and it seemed to worked. My code for you and #Anand
No Errors, except for empty Lists. But thats because I didn't fed it any information. So, there shouldn't be a problem.
#Grohl maybe try my code and comment where the error is displayed. This should be the most easy way to find the problem.
TestClass which represents class GetKoord
namespace TestForm
{
class TestClass
{
public TestClass()
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
}
}
}
The GetVertElementasList
namespace TestForm
{
class GetVertElementasList
{
private List<vertEl> vertElementList = new List<vertEl>();
public List<vertEl> vertList(DataGridView VertElementer)
{
for (int i = 0; i < VertElementer.Rows.Count - 1; i++)
{
vertElementList.Add(new vertEl
{
elNr = (int)VertElementer.Rows[i].Cells[0].Value,
p1 = (double)VertElementer.Rows[i].Cells[1].Value,
p2 = (double)VertElementer.Rows[i].Cells[2].Value,
z1 = (double)VertElementer.Rows[i].Cells[3].Value,
z2 = (double)VertElementer.Rows[i].Cells[4].Value,
heln1 = Convert.ToDouble(VertElementer.Rows[i].Cells[5].Value),
heln2 = (double)VertElementer.Rows[i].Cells[6].Value
});
}
return vertElementList;
}
}
//Some other stuff
}
Last but not least. the code from the button click event:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
DataGridView tmp = new DataGridView();
GetVertElementasList getList = new GetVertElementasList();
var TEST = getList.vertList(tmp);
MessageBox.Show(TEST[5].p2.ToString());
TestClass tmpClass = new TestClass();
}
}
To #Grohl EDIT2:
It hurts to see that you are trying to read data without checking if there is any. In such cases, check!
Like this:
if(TEST.Count() >= 3)
{
MessageBox.Show(TEST[2].elNr.ToString());
}
It should debug at be smooth at runtime. I think your problem is getting the data.
Make sure you load the needed data and check if it isn't null.

Is there a way to assign values to a combobox without using a datasource?

I'm using Entity Framework to throw together a combobox with values from my MSSQL database using the following
using (var context = new Entity())
{
var things = (from p in context.Stuff
where ((p.SourceId == StuffId && p.Domain.Value == "Stuff")
|| (p.SourceId == OtherStuffId && p.Domain.Value == "OtherStuff"))
&& p.Done == true orderby p.StuffId
select p);
foreach(var stuff in things)
cboRejectTask.Items.Add(stuff.StuffId + ": " + stuff.StuffType.Description + " " + stuff.StuffType.DisplayName);
}
I'd like to assign values to each row so that when it comes time to grab what the user selected I don't have to do string manipulation to get what I want. I don't want to use a datasource if possible.
Solution:
Given there isn't a better way to do this than creating a custom class I went ahead and did so using the selected answer's code modified a bit for long-term use. (note: you could really use any given object as long as ToString() returned the "display text" and it had a Tag or any writeable property compatible with your needs)
public class ComboBoxItem
{
public string Display;
public object Value;
public override string ToString()
{
return Display;
}
}
Given this code I can now change my code to the following:
using (var context = new Entity())
{
var things = (from p in context.Stuff
where ((p.SourceId == StuffId && p.Domain.Value == "Stuff")
|| (p.SourceId == OtherStuffId && p.Domain.Value == "OtherStuff"))
&& p.Done == true orderby p.StuffId
select p);
foreach(var stuff in things)
cboRejectTask.Items.Add(new ComboBoxItem() { Display = stuff.StuffId + ": " + stuff.StuffType.Description + " " + stuff.StuffType.DisplayName, Value = stuff.StuffId });
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var cbi1 = new ComboBoxItem("Item 1") { Id = 1 };
var cbi2 = new ComboBoxItem("Item 2") { Id = 2 };
var cbi3 = new ComboBoxItem("Item 3") { Id = 3 };
comboBox1.Items.Add(cbi1);
comboBox1.Items.Add(cbi2);
comboBox1.Items.Add(cbi3);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
var id = ((ComboBoxItem)comboBox1.SelectedItem).Id;
MessageBox.Show(id.ToString());
}
}
public class ComboBoxItem
{
private readonly string text;
public int Id { get; set; }
public ComboBoxItem(string text)
{
this.text = text;
}
public override string ToString()
{
return text;
}
}
I think you might find this usefull:
comboBox1.Items.Add(1);
comboBox1.Items.Add(2);
comboBox1.Items.Add(3);
private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
//this will set what gets displayed in the combobox, but does not change the value.
e.Value = "display value";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show((sender as ComboBox).SelectedItem.ToString());
}

Categories

Resources