I am trying to fill a comboBox and a secondary form from a separate class file and I think I have the basics wrong.
The following is shortened to show the bones of what I have and what I think I may be doing wrong. I am not sure if I should be using List<> to populate the comboBox or an Array and suspect in either case my method declaraction is wrong and I cannot find a reference to the comboBox to populate from within the foreach loop.
OK the program.cs for my settings Form. This is not the main form but is the one I am looking to populate when a user select the comboBox.
Program.cs
class Settings
{
public partial class Settings : Form
{
// a bunch of String declarations used throughout
public Settings()
{
InitializeComponent();
}
}
}
The method within a class in a separate file is
Functions.cs
class functions
//This is a separate class to the Settings Form but same namespace.
{
//some global variables here
public string getDomain(string webURL)
{
//more variable declarations
//webURL is a value from the Settings Form
//code to send query to website, get the response and filter the response.
//This is the response filter
foreach (XmlNode node in xmlDoc.SelectNodes("//DAV:domains/DAV:domain", nsmgr))
{
strNode = node.InnerText;
responseString += strNode + " ";
list.Add(strNode);
//I would like to simply Add.Items(strNode) to the Settings.Form.cbxDomains but not as simple as this.
}
//this returns all the correct information as a space separated string.
return responseString;
}
}
From Update UI from a different thread in a different class
I thinks there are 2 things I should do.
1. change the form initialisation from InitilizeComponents() to
settingsWindow = new MyForm();
Application.Run(form);
Then simply call Settings.settingsWindow.cbxDomain.Add>items(responseString);
But do I also need to change the actual method to something like
public void List<String> getDomain(string webURL)
I am so confused. Most examples show it the other way of updating the class from the combo not the other way and some say create it as an array.
I actually think it could even be trimmed down further into one or 2 lines instead of the foreach, but that is way beyond my skillset at this time.
Here is how you could populate your combobox from another form.
I will use example since I do not know you code structure but you will get the point.
public class User //Custom generic class
{
public int _Id { get; set; }
public string _Name { get; set; }
}
public class Functions
{
public static List<User> PopulateComboboxWithUsers()
{
List<User> list = new List<User>();
foreach(var something in somethingBig) //You can change this if you re reading form XML with it's variables or something else
{
list.Add(new User { _Id = something.Id, _Name = something.Name };
}
return list;
}
}
public class Settings
{
public Settings()
{
InitializeComponents();
comboBox1.DataSource = Functions.PopulateComboboxWithUser();
comboBox1.DisplayMember = "_Name";
comboBox1.ValueMember = "_Id";
}
}
Other approach is to do the same function expect you will pass comboBox to it and you will do assigning inside it but I think this is more flexible.
Related
I would like to know how can I create an array of Circular Progress Bars and access its properties within the array, like CircularProgressBar[i].text and CircularProgressBar[i].value.
I tried to use object array but I can't access the properties of circular progress bar within the for loop, what I also tried is to make to arrays one is type string and it has all the CircularProgressBars.text, and the Other one is the type INT which contains CircularProgressBar.value, but it didn't work, nothing changed in the form.
CircularProgressBar.CircularProgressBar[] cbpArray = new CircularProgressBar.CircularProgressBar[] { shifts1.circularProgressBarNeeShift1, shifts1.circularProgressBarNeeShift2, shifts1.circularProgressBarNeeShift1 };
public Form1()
{
InitializeComponent();
}
image
Okay, since you are trying to reference an item that is in a user control you need to add an accessor inside your UserControl .cs file. I believe it is called shift1.cs for you.
Note: cpb is the name that I gave the CircularProgressBar inside the UserControl shifts1.
public partial class shifts1 : UserControl
{
public CircularProgressBar.CircularProgressBar CPB
{
get
{
return cpb;
}
set
{
cpb = value;
}
}
public shifts1()
{
InitializeComponent();
}
}
Then you will use the name for each user control from your form. In my case I named mine formCPB1 and formCPB2.
CircularProgressBar.CircularProgressBar[] arr = new CircularProgressBar.CircularProgressBar[]
{ formCPB1.CPB, formCPB2.CPB };
Once you have the array you can access them by using the name of the array.
arr[0].Text = "test";
arr[1].Text = "asdf";
I hope you can help out a fellow programmer. Basically, I want the user input from the Rich Text Box (taskNameRTB) to be assigned to the taskName; string variable in my class taskStructure which is in form1 shown below:
public partial class Form1 : Form
{
public class taskStructure
{
public string taskName;
public string taskDescription;
public int Priority;
public string dateAndTime;
}
public List<taskStructure> TasksArray = new List<taskStructure>(); //Declared a list data structure
In my second form which is where the user enters everything related to the task, I want to send this information to the list after the 'Create Task' button has been clicked:
private void createTaskBtn_Click(object sender, EventArgs e)
{
Form1 welcomeForm = new Form1();
welcomeForm.TasksArray[0].taskName = taskNameRTB.Text;
welcomeForm.TasksArray[0].taskDescription = taskDescRTB.Text;
}
However, when I do this I get a ArgumentOutOfRangeException and I do not understand why. I have also tried these:
welcomeForm.TasksArray[0].Add(taskDescRTB.Text);
welcomeForm.TasksArray.Insert(0, taskNameRTB.Text);
welcomeForm.TasksArray.Add(taskDescRTB.Text);
taskNameRTB.Text = welcomeForm.TasksArray[0].taskName;
But the ones that run come up with the same error ArgumentOutOfRangeException and some of them don't work, such as:
welcomeForm.TasksArray[0].Add(taskDescRTB.Text);
I'm aware that the list has not been initialized, but how can I initialize it when it doesn't allow me to initialize it with user input...
Any light you can shed on this will be really helpful
Kind Regards,
Kieran
You need to add a new taskStructrue to the list.
welcomeForm.TasksArray.Add(new taskStructure
{
taskName = taskDescRTB.Text,
taskDescription = taskDescRTB.Text
});
But personally I'd rewrite that class to follow naming conventions and to use properties instead of public fields.
public class TaskStructure
{
public string TaskName { get; set; }
public string TaskDescription { get; set; }
public int Priority { get; set; }
public string DateAndTime { get; set; }
}
have you tried
welcomeForm.TasksArray.Add(new taskStructure(taskDescRTB.Text));
I don't know what taskStructure is, but you need to fill TasksArray with types of it.
Your TaskStructure is a class, and you are putting all TaskStructure objects into a list,
public List<taskStructure> TasksArray = new List<taskStructure>(); //Declared a list data structure
Does your Form1() have a constructor that calls InitializeComponents()?
If so, you could try adding TasksArray = new List<taskStructure>() right below InitializeComponents(), because it looks like you're trying to access the list data structure that hasn't been initialized with new.
Alternatively
As another user noted, you can create a constructor class for TaskStructure like this:
public TaskStructure(RTB rtb1, rtb2, rtb3) //where RTB is the rich text box type
{
taskName = rtb1.text;
taskDescription = rtb2.text;
//and so on.
}
Then you can do TaskArray.add(new TaskStruture(rtb1,rtb2,rtb3).
Thrid Edit
Just realized your TaskArray is actually a List, which in C# (and Java), you cannot access it with an index like TaskArray[0], you have to use getter and setter methods, which in this case is TaskArray.add(), and TaskArray.get(0), you're getting ArgumentOutOfRangeException because you're trying to access a List using square indexes like this --> [0]. You can actually access a list doing list1, as pointed out by another user.
Here's a good tutorial on C# lists, by DotNetPerls
I am having problems getting the items from my list into a textbox. I’m using Windows forms in Visual Studio.
I have one form with some textboxes and put the inputs to a list. The list contains customers and the user gives the customer an id from one of the textboxes. Now I want to get all the items from the list to the next form.
I have the list in a public class:
public class myClassCustomer
{
public List<customerInformation> cusInformation = new List<customerInformation>();
public class customerInformation
{
public string customerId { get; set; }
public string phoneNumber { get; set; }
public string adress { get; set; }
}
And the code for saving the inputs in form1:
myClassCustomer myClassCustomer = new myClassCustomer()
customers.cusInformation.Add(new myProject.myClassCustomer.customerInformation
{
customerId = txtCustomerId.Text,
phoneNumber = txtPhonenumber.Text,
adress = txtAdress.Text
});
Now in form2 this is what I have written so far:
public form2()
{
InitializeComponent();
myClassCustomer myClassCustomer = new myClassCustomer();
}
Does anyone know how to get all the items from the list?
I'm presuming that the question boils down to how to "get all of the items from the list to the next form", rather than the title suggests "get items from list by id".
The question "Anyone knows how to get all the items from the list?" is a bit tautological because the list already is all of the items.
So I am going to focus on answering your question about the list items being available to the next form. I presume that "Customers" is essentially just a List, and if it isn't, you should probably consider using that instead of a homebrew list class unless you have a very specific requirement otherwise. At the very least, I am hoping that the customers class implements the IEnumerable interface.
In order for this other form to be able to access your list of customers, you need to be making that information available somehow: for instance, you could change the other form's constructor to require a list of customers. Then, when this original form invokes the second form, it must pass in that list it has presumably populated as a parameter.
There are a few other ways this information could be propagated around your application but it sounds like you're just at a beginner level, so the method given above is probably the simplest.
Perhaps you could clarify your question if this does not answer it.
Edit: Some of your own edits have changed the code I was commenting on. It now appears that you're not after a list, but the advice is the same; instead of passing a List, you're just passing a myClassCustomer.
Just define a public property in your form1
public List<customerInformation> AllCustomers
{
get { return yourList; }
}
When opening your Form2 from Form1 use this code:
Form2 f2 = new Form2();
f2.Show(this);
Then you can access your customers from Form2:
var myCustomerList = ((Form1)Owner).AllCustomers;
I'm working on a Winforms application and I have a bindinglist of objects that I want to bind to a listbox. I got this to work, but what I want to do next, is only display items where a particular property is true.
So I have a class with a bindinglist
class DataBuilder
{
public BindingList<TableSet> allTableSets = new BindingList<TableSet>();
}
And a class TableSet with some properties
class TableSet
{
public string TableSetName {get; set;}
public bool IsPopulated {get; set;}
}
And now on my form, I want to bind a listbox to the allTableSets, but only show the items where IsPopulated == true
What I have so far on my form just shows all the items in the allTableSets list
public partial class MainForm : Form
{
DataBuilder dataBuilder = new DataBuilder();
{
this.populatedTableSetsListBox.DataSource = dataBuilder.allTableSets;
this.populatedTableSetsListBox.DisplayMember = "TableSetName";
}
}
I've been looking around the web but haven't found anything that seems similar to what I"m trying to do. Any suggestions or alternate methods are greatly appreciated. Thank you
Try this: in your DataBuilder class, have a function that returns a subset of your items based on your filter condition.
For example, in your DataBuilder class:
public BindingList<TableSet> someTableSets()
{
BindingList<TableSet> someTableList = new BindingList<TableSet>();
foreach (TableSet TS in allTableSets)
if (TS.IsPopulated == true)
someTableList.Add(TS);
return someTableList;
}
Then, in your MainForm, instead of setting the DataSource to allTableSets, set it equal to the result of the someTableSets() function:
this.populatedTableSetsListBox.DataSource = dataBuilder.someTableSets();
I am trying to copy an object onto the windows clipboard and off again. My code is like this:
Copy on to clipboard:
Clipboard.Clear();
DataObject newObject = new DataObject(prompts);
newObject.SetData(myString);
Clipboard.SetDataObject(newObject);
Where prompts is a List<Data.Sources.PromptResult> collection.
Copy off clipboard:
IDataObject dataObject = System.Windows.Forms.Clipboard.GetDataObject();
if (dataObject.GetDataPresent(typeof(List<Data.Sources.PromptResult>)))
{
Type type = typeof(List<Data.Sources.PromptResult>);
Object obj = dataObject.GetData(type);
return (List<Data.Sources.PromptResult>)dataObject.GetData(type);
}
The GetFormats() shows the format as being in the list and the GetDataPresent(List<Data.Sources.PromptResult>) returns true but if I try to get the object out of the Clipboard class with GetData(List<Data.Sources.PromptResult>) I get a return of null.
Does anyone have any idea what might be wrong?
OK I tried to add list of my user type to clipboard and get it back...
Here is what I tried:
My User Class:
public class User
{
public int Age { get; set; }
public string Name { get; set; }
}
Rest of Code:
// Create User list and add some users
List<User> users = new List<User>();
users.Add(new User { age = 15, name = "Peter" });
users.Add(new User { age = 14, name = "John" });
// Lets say its my data format
string format = "MyUserList";
Clipboard.Clear();
// Set data to clipboard
Clipboard.SetData(format, users);
// Get data from clipboard
List<User> result = null;
if (Clipboard.ContainsData(format))
result = (List<User>)Clipboard.GetData(format);
...and result was null :)
...until I marked User class as Serializable
[Serializable]
public class User
{
//...
}
After that my code worked.
Ok its not the answer but maybe it helps you some how.
#Reniuz thanks for your help it has helped me to work out the answer.
In order to get the text and custom object data out of the Clipboard with multiple formats I have implemented the IDataObject interface in my own class. The code to set the data object must have the copy flag set like this:
Clipboard.Clear();
Clipboard.SetDataObject(myClassThatImplementsIDataObject, true);
To get the data out again the standard text can be retrieved using:
Clipboard.GetText();
The data can be retrieved using the data method:
Clipboard.GetData("name of my class");
The other point that was helpful was to test that the object I was putting into the clipboard could be serialized by using the BinaryFormatter class to perform this test... If an exception is thrown that copying to the clipboard would also fail, but silently.
So my class has:
[Serializable]
public class ClipboardPromptsHolder : IDataObject
{
...
}
I had a similar scenario and after marking my class as serializable I got it to work.
So try putting the Serializable attribute on your class Data.Sources.PromptResult.
I found out that, if your class is derived from a different class, the base class also needs to be made [Serializable], otherwise that recipe does not work. In my case, it was something like
public abstract class MyAbstractUser
{
...
}
[Serializable]
public class MyUser : MyAbstractUser
{
...
}
When I tried to exchange values of MyUser over the clipboard, it did not work, but when I added [Serializable] to MyAbstractUser, it did work.
I came across this while trying to send a list of items to my clipboard. What I needed was the string representation of those items, not the entire object. I tried a few of the suggestions here, to no avail. However, I did come up with my own solution and I wanted to share it. See below.
public static void CopyToClipboard<T>(this IEnumerable<T> items)
{
StringBuilder stringBuilder = new StringBuilder();
foreach (T item in items)
stringBuilder.Append(item.ToString()).AppendLine();
Clipboard.SetText(stringBuilder.ToString());
}
Add this as an extension method and be sure to override your custom Type's ToString() method.