Combobox Examples - c#

I am getting the following error for foreach
Foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'
I am making any syntax error
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;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Namepopu_SelectedIndexChanged(object sender, EventArgs e)
{
// this.textBox1.Text = Namepopu.Text;
// this.textBox1.Text = " ";
foreach (int i in Namepopu.SelectedItem)
this.textBox1.Text += Namepopu.Text[i];
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}

Perhaps you meant to do this?
for (int i = 0; i < Namepopu.Items.Count; ++i)
{
this.textBox1.Text += Namepopu.Items[i].ToString();
}

What's the contents of Namepopu.SelectedItem ? An array ? A generic list ? Cast it to it's original type first, then iterate over it in your foreach.
For example:
List<int> myValues = (List<int>)Namepopu.SelectedItem;
foreach (int i in myValues)
{
...
}
or
int[] myValues = (int[])Namepopu.SelectedItem;
foreach (int i in myValues)
{
...
}

textBox1.Text = string.Empty;
foreach (var item in Namepopu.SelectedItems)
textBox1.Text += item.ToString();

The problem is that you are trying to get the enumerator for something that does not implement the IEnumerator interface. For a listing of the collection types you can iterate using a for each this MSDN article is useful (http://msdn.microsoft.com/en-us/library/dscyy5s0.aspx).

Related

How do I get a string from a TextBox in VS and then compare it to an integer using an if statement?

Alright, I'm pretty new to C# and I'm trying to figure out how I could grab a string or a number from my TextBox in Visual Studio(Windows Form Application) and then figure out if that string is 0.
I've tried doing
if(Calculations.Text == 0)
{
Calculations.Text = 1
}
but to my avail it did not work.
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 WindowsFormsApp1
{
public partial class Calculatrice : Form
{
public Calculatrice()
{
InitializeComponent();
}
private void One_Click(object sender, EventArgs e)
{
if(Calculations.Text)
{
}
}
private void Calculatrice_Load(object sender, EventArgs e)
{
}
}
}
This is all I have right now I'm pretty stuck.
I want to be able to use the if statement to make comparisons with int values.
You should enclose your string in quotes before using them
if(Calculations.Text.Trim () == "0")
{
Calculations.Text = "1";
}
//Example:if Calculations is your textbox id,then
string input = calculations.text.tostring();
//then compare zero with " "
if(input == "0")
{
calculations.text= 1;
}
A user can put anything in a TextBox. Use TryParse which will provide a zero even if it fails (returns false)
private void OPCode()
{
int.TryParse(Calculations.Text, out int i);
if (i == 0)
{
Calculations.Text = 1.ToString();
}
}

How do I make my DataGridView read info of a text file C#

so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present code:
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 WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.

I can't assign values to the "List Collection" in my class

This is my class That contains two List collections that will store input that is sent over from my main form. As of right now it have no compiling errors in my class, however I am not sure if it is correct. What it is suppose to do is receive input and display it when called.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmployeeRoster
{
public class Employee
{
List<string> name = new List<string>();
List<int> iDnumber = new List<int>();
public void setEmployeeName( List < string> employeenames, string names)
{
employeenames.Add(names);
employeenames = name;
}
public List <string> getEmployeeName()
{
return name;
}
public void setEmployeeNumber( List < int > employeeId, int numbers)
{
employeeId.Add(numbers);
employeeId = iDnumber;
}
public List<int> getEmployeeName()
{
return iDnumber;
}
}
}
I am Trying To assign names to my list that I have created in my class above, However I am trying this code below and I am receiving 2 errors
// Error Cannot implicitly convert type 'System.Collections.Generic.List' to 'string'
// Error No overload for method 'setEmployeeName' takes 1 arguments
What Is the correct way to send arguments into Class in order to fill my list?
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;
namespace EmployeeRoster
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Employee chart = new Employee();
List < Employee > names = new List < Employee > ();
text1.Text = names; // Error Cannot implicitly convert type 'System.Collections.Generic.List<EmployeeRoster.Employee>' to 'string'
chart.setEmployeeName(names); // Error No overload for method 'setEmployeeName' takes 1 arguments
}
}
}
text1.text = Convert.ToString(names);
You can convert it on the fly like that.
I don't believe you need to pass the collection over to the class. The class can instantiate and add the strings to the collection for you.

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.

Visual Studio gives a NullReferenceException when trying to add my control!

Here's the error:
It says the source of the exception is on Line20 of my class. Here is my class:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections.ObjectModel;
namespace WebServiceScanner
{
public partial class imageList : UserControl
{
private int XPosition = 0;
public imageList()
{
InitializeComponent();
Images.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Images_CollectionChanged);
}
public ObservableCollection<selectablePicture> Images { get; set; }
public void AddImage(selectablePicture image)
{
Images.Add(image);
}
public void RemoveImage(selectablePicture image)
{
Images.Remove(image);
}
public void MoveImageLeft(int index)
{
selectablePicture tmpImage = Images[index];
Images[index] = Images[index - 1];
Images[index - 1] = tmpImage;
}
public void MoveImageRight(int index)
{
selectablePicture tmpImage = Images[index];
Images[index] = Images[index + 1];
Images[index + 1] = tmpImage;
}
void Images_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
RedrawImages();
}
private void RedrawImages()
{
foreach (var picture in Images)
{
picture.Location = new Point(XPosition + panel1.AutoScrollPosition.X, 0);
XPosition += 130;
panel1.Controls.Add(picture);
}
}
}
}
Maybe I'm doing something dumb like setting an event handler at the constructor. Any ideas? This user control isn't really that complex, so there are few places where something could be wrong.
If you guys need more information please let me know.
Add a statement to instantiate Images.
public imageList()
{
InitializeComponent();
Images = new ObservableCollection<selectablePicture>();
Images.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Images_CollectionChanged);
}
I'm guessing it is something to do with the fact that Images isn't set to any value so the control is trying to render it for DesignView but Images is null hence the NullReferenceException. It's probably the code in the Constructor when it tries to register against the Images which will probably run before any injection code setting images.
Does < selectablePicture > have a parameterless public constructor? And are you instancing Images?

Categories