I have what to me looks like an implicitly typed object array and variables of different types (string, int). On clicking the button on my form, I can display a message for each array item. But, I'd like to be able to add each of those items to a listbox. The latest version of my code(see below after trying many different things) has produced the error "Error 1 Use of unassigned local variable 'x' "
How can I add each of those values of different types to the list box?
Thanks
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;
namespace TheWriteLineMethodForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string x;
Object[] values = { true, 12.632, 17908, "stringValue",
'a', 16907.32m };
foreach (var value in values)
//Console.WriteLine(value);
// MessageBox.Show(value.ToString());
x = value.ToString();
listBox1.Items.Add(x);
}
}
}
A major glitch in your code, you forgot brackets
foreach (var value in values)
//Console.WriteLine(value);
// MessageBox.Show(value.ToString());
x = value.ToString();
listBox1.Items.Add(x);
So your code is equivalent to
string x;
foreach (var value in values) { x = value.ToString(); }
listBox1.Items.Add(x);
When you do your listBox1.Items.Add(x), it only add the last value "16907.32m"
I should say the simplest way is to use
values.ToList().ForEach(x => listeBox1.Items.Add(x));
Related
hi im sorta new to doing projects myself but one of my first tasks was to make a btec grade to ucas points converter by allowing the user to select their grade from the combobox and it would show in a label the correlating grade
however i dont know how to get the selected combobox item to change the label for each different grade
i tried using a an if statement but i realised that it comes up with error CS0029
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;
namespace btec_to_ucas
{
public partial class Form1 : Form
{
string PPP = "48";
string MPP = "64";
string MMP = "80";
string MMM = "96";
string MMD = "112";
string DDM = "128";
string DDD = "144";
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1 = PPP)
{
label1.Text = PPP;
}
}
}
}```
Problem is here: if (comboBox1 = PPP). In this case, comboBox1 is the whole combo box object, with its items, selected index, size, etc. That will never be equal to the string "48". You want to look at the value that has been entered. Try comboBox1.SelectedText.
See:
https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.combobox?view=netcore-3.1
I added 3 items to the comboBox in the form, using the Items property. These items are: Item1, Item2, Item3.
When I select any of these 3 items in the comboBox, I want it to show a messagebox that contains the value of the first attribute of the corresponding object.
For example when i click Item1, I want it to show me attribute "CNP1" from object a1, when I click Item2, to show me attribute CNP2 from object a2 and so on.
I think that I might connect each item in the comboBox with one of the 3 object created, not just write down these names(Item1,Item2,Item3) but I don't know how.
Also, these 3 items are created due to a class I created in the same project.
I only have a class, a form and the main Program in this project.
So, how can I connect a comboBox Item to one of these objects, especially with only one attribute of that object. Thank you.
using System;
using System.Collections;
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;
namespace IncercareEX2015
{
public partial class PreluareDate : Form
{
ArrayList listaAbonati;
AbonatTelefonic ab;
public PreluareDate()
{
InitializeComponent();
double[] vectMin = new double[4] { 12, 15, 50, 20 };
AbonatTelefonic a1 = new AbonatTelefonic("CNP1", "Nume1", "Adresa1", "tel1", "tip1", vectMin);
double[] vectMin3 = new double[2] { 100, 130 };
AbonatTelefonic a3 = new AbonatTelefonic("CNP3", "Nume3", "Adresa3", "Tel3", "Tip3", vectMin3);
double[] vectMin2 = new double[3] { 200, 80, 150 };
AbonatTelefonic a2 = new AbonatTelefonic("CNP2", "Nume2", "Adresa2", "Tel2", "Tip2", vectMin2);
///GENERARE COLECTIE DE OBIECTE
ArrayList listaAbonati = new ArrayList();
listaAbonati.Add(a1);
listaAbonati.Add(a3);
listaAbonati.Add(a2);
listaAbonati.Sort();
}
private void comboBox1_nume_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (object o in listaAbonati)
MessageBox.Show(o.ToString());
}
}
}
Assuming that your code compiles and shows the o.ToString() when the selected index changes you would want to switch from using an ArrayList to a generic List, in your case a List which will allow you to access the properties of your entities without the need to casting in the event handler. Here's the relevant portion of your code:
List<AbonatTelefonic> listaAbonati;
public PreluareDate()
{
///GENERARE COLECTIE DE OBIECTE
listaAbonati = new List<AbonatTelefonic>();
listaAbonati.Add(a1);
listaAbonati.Add(a3);
listaAbonati.Add(a2);
listaAbonati.Sort();
}
private void comboBox1_nume_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (AbonatTelefonic at in listaAbonati)
MessageBox.Show(at.YourDesiredPropertyNameGoesHere);
}
You can use SelectedIndex to get AbonatTelefonic. I hope it will help you.
private void comboBox1_nume_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1_nume.SelectedIndex != -1)
{
AbonatTelefonic at = (AbonatTelefonic)listaAbonati[comboBox1_nume.SelectedIndex];
MessageBox.Show(at.YourAttribute);
}
}
Add public override string ToString() on your AbonatTelefonic class and add the code return {first attrib variable};
Reference for you: https://msdn.microsoft.com/en-us/library/ms173154(v=vs.80).aspx
Hope this helps.
I made a masked textbox for saving numbers with the mask (999) 000-0000 and I want to show only numbers in label but when I do that, it also copies the parantheses and lines.
I know it copies all the text. How I can only copy numbers entered not with mask?
(windows form)
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;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = maskedTextBox1.Text;
}
}
}
One solution is to set TextMaskFormat to ExcludePromptAndLiterals just before reading it's value:
maskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
Console.WriteLine(maskedTextBox1.Text);
//will print 3123 when value in the mask textbox is (31) 23 for mask (00) 00
And after this set Format back:
maskedTextBox1.TextMaskFormat = MaskFormat.IncludeLiterals;
Even if you won't set format back to IncludeLiterals, UI control still would show masked text (31) 23 and will work as usual. This is done if your other logic relies on masked Text field.
So if you don't have such dependencies, you can set this value right in the Visual Studio designer in properties window for maskedTextBox1
so i was working with a text file data that contains a lot of simple lines and i want to put them on the list view exatly the same way as the listbox do. I need that because after i loading a long list on listbox, even it showing all my items, i cannot make a FindString() on it. i attached the comand to a combo box, and with other small lists it worked, but with this larger, seems that index reference doesn't work because of listbox limit.
So i was wondering if is possible to put, as example:
line1
line2
line3
line4
My text files hasn't this dots, i pu them just to make the example vertical.
On a list view. i used on listbox the method file.readllines to get it loading to it, and if exists a string find method to help me get the text on the lines. What should i do?
You can write the searcher you want by yourself.
It's very easy.
Just iterate on each data that exists in your ListView.
Then check your condition through an if-statement and do anything you want with the result!
Like this :
this.listView1.Items.Add("Test1");
this.listView1.Items.Add("Test2");
int Index = 0;
foreach (ListViewItem t in this.listView1.Items)
{
if (t.Text == "Test1")
Index = t.SelectedIndex;
break;
}
this.listView1.Items[Index].Selected = true;
I added couple of items to the ListView then iterate on it's items using a foreach, filter the items using an if-statement and finally show the item that I want.
You have to add an eventhandler. For example for the event of the ListView Load.
Then in the event handler you could load the contents of the file using the File class.
For example you could do it like this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// ListView Loaded - Eventhandler
private void ListView_Loaded(object sender, RoutedEventArgs e)
{
string[] lines = File.ReadAllLines("E:\\test.txt");
foreach (string line in lines)
{
listview.Items.Add(line);
}
}
}
}
I have just tested the solution and it works fine.
I hope I got your intention.
thanks a lot of helping me, but i gandle it, i search a lot for extending the limit of listbox but no one was capable to help me out, but with your "foreach" code, this new way to search helped me to select my string on listbox, here's the code using a combo box to evertime updated get me the selected value from a gourgeous list:
declaring:
string result;
and then the combobox event:
private void comboBox1_TextUpdate(object sender, EventArgs e)
{
foreach (string item in listBox1.Items)
{
listBox1.SelectionMode = SelectionMode.One;
if (item == comboBox1.Text)
{
result = item;
}
}
listBox1.SelectedItem = result;
}
I'm writing a simple first app using Winforms, C#, VS2010, and Entity Framework. Basically, I have a rich DB I'm tapping, and I've already set up the framework, successfully enough to populate a DataGridView control with a subset of the Work Order table.
Now, I want to place a combo box on the form ("cbProjectID") whose value is ProjectID and DisplayValue is ProjectNbr. I only want to put projects in the combo box list that are related to WorkOrders, and only unique ProjectIDs within that set (a project may have dozens of work orders....)
I'm assuming I need to generate a list from EF, using LINQ. I'm pretty new at LINQ, and I'm not figuring it out...Here's my code so far...
using System;
using CPASEntityFramework;
using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace BrowseWorkOrders
{
public partial class BrowseWOs : Form
{
public BrowseWOs()
{
InitializeComponent();
}
private void BrowseWOs_Load(object sender, EventArgs e)
{
var context = new CPASEntities();
var query = context.tblWorkOrders.Where(c => c.ProjectID==8);
tblWorkOrderBindingSource.DataSource = query.ToList();
// Now, I want to load up the Combo Box with all the projects in the Work Order Table
}
}
}
I've been through the net trying to find a method I understand, but I'm failing. Perhaps someone can help me out. Here's my Datasource (I assume I should NOT use tblProject, but instead use the tblProject inside tblWorkOrder in order to get my subset...)
Any help and/or guidance would be appreciated.
Here's the code now...
namespace BrowseWorkOrders
{
public partial class BrowseWOs : Form
{
public BrowseWOs()
{
InitializeComponent();
}
private void BrowseWOs_Load(object sender, EventArgs e)
{
// Following loads up all Projects into the cbProjectID Combo Box
var context = new CPASEntities();
var PrID = context.qryProjectIDNbrDescs.ToList();
cbProjectID.DataSource = PrID;
cbProjectID.ValueMember = "ID";
cbProjectID.DisplayMember = "ProjectNbr";
}
private void cbProjectID_SelectedIndexChanged(object sender, EventArgs e)
{
var context = new CPASEntities();
var query = context.tblWorkOrders.Where(c => c.ProjectID == (int)cbProjectID.SelectedValue).ToList();
tblWorkOrderBindingSource.DataSource = query;
}
}
}
You need the tblProject on the top because the other is for a single WorkOrder only. However, you need to filter the list with those who have at least on WorkOrder:
var projects = context.tblProjects.Where(p => p.tblWorkOrders.Any()).ToArray();
cbProjectID.DataSource = projects;
cbProjectID.ValueMember = "ProjectID";
cbProjectID.DisplayMember = "ProjectNbr";