Append clipboard text to a listbox - c#

So I created a variable to hold my clipboard text and I have no idea on how to append it to a listbox.
This is as far as I got..
private void clipboardBtn_Click(object sender, EventArgs e)
{
string items = Clipboard.GetText();
List<string> _items = new List<string>();
_items.AddRange(items);
}
but that throws me this error..
Argument 1: cannot convert from 'string' to
'System.Collections.Generic.IEnumerable'
What's causing this and how do I fix it? Is this even the correct way of appending text to the listbox?
-UPDATE-
I got this now but everytime I click the button it overwrites the old one instead of appending a new item to the listbox
string items = Clipboard.GetText();
List<string> _items = new List<string>();
_items.Add(items);
listBox1.DataSource =_items;
How do i append a new item?

Clipboard.GetText has the signature
public static string GetText()
but List<T>.AddRange has the signature
public void AddRange( IEnumerable<T> collection )
So essentially you're trying to add a string as an IEnumerable<T> which gives you the above error.
Better use List<T>.Add for that purpose like that:
_items.Add(items);

your question is about List object and not about ListBox control.
the AddRange() method requires a collection, you can transform your string to a collection (Array) by using Split.
private void clipboardBtn_Click(object sender, EventArgs e)
{
string YourGetClipBoardTextString = "aaa;bbb;ccc;ddd";
List<string> _items = new List<string>();
_items.AddRange(YourGetClipBoardTextString.Split(';').ToArray()); // you can split the string by any char seperator ";" " ", "," etc...
}
if you dont need to split the string just use the Add() method:
_items.Add(YourGetClipBoardTextString);
After your update, you can append new items to a listbox in that manner:
foreach (string itm in _items)
{
listBox1.Items.Add(itm);
}

since you're creating new "_items" on every click, you cannot see the old items. try like this,
List<string> _items = new List<string>();
private void clipboardBtn_Click(object sender, EventArgs e)
{
string items = Clipboard.GetText();
_items.Add(items);
listBox1.DataSource =_items;
}
_items declared outside of method scope.

Your problem is that you are initializing a new list each time:
string items = Clipboard.GetText();
List<string> _items = new List<string>();//<New list here results in removal of existing item
_items.Add(items);
listBox1.DataSource =_items;
Try something like this:
string items = Clipboard.GetText();
List<string> _items = listBox1.DataSource as List<string>;// You may have type casting issues here -
_items.Add(items);
listBox1.DataSource =_items;

First you need to split the clipboard contents into strings for each line, then you need to add them to the list box:
string[] items = Clipboard.GetText().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
listBox1.Items.AddRange(items);
If you don't want to have a separate listBox item for each line, just do this:
listBox1.Items.Add(Clipboard.GetText());

Related

“Repeated” data displayed in datatable

I want to display my List<string> in a datatable, from another form. The data from the List<string> is from textbox and combobox. However, the data from textbox is never repeated but the combobox might be similar with previous data displayed. And if this happened, the data displayed in datatable will be “repeated” (I’m unsure on how to describe it). Here is the actual outcome. I would like to see my displayed data to be like this. Below is my code:
Transavestate - class that hold my List
public static List<string> transnumber_list = new List<string>();
public static List<string> combos_list = new List<string>();
Form1 - form that user input values of textbox and combobox
private void button1_Click(object sender, EventArgs e)
{
//Save values in the List
Transavestate.transnumber_list.Add(Textbox1.Text)
Transavestate.combos_list.Add(comboBox2.SelectedItem.ToString());
//Go to Form 2
this.Hide();
Form2 f2 = new Form2 ();
f2.Show();
}
Form2 - form to display values of textbox and combobox
private DataSet ds;
private DataTable dt;
//Method to insert data into dtg1
private void CreateDataSet()
{
ds = new DataSet();
dt = new DataTable("Vehicle Number");
dt.Columns.Add("Column 1", typeof(string));
dt.Columns.Add("Column 2", typeof(string));
foreach (var item in Transavestate.transnumber_list)
{
foreach (var items in Transavestate.combos_list)
{
dt.Rows.Add(item, items);
}
}
ds.Tables.Add(dt);
this.dataGridView1.DataSource = dt;
dataGridView1.AllowUserToAddRows = false;
}
//To run the method
private void dataGridView1_VisibleChanged(object sender, EventArgs e)
{
CreateDataSet();
}
//Go back to Form1
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
Form1 f1 = new Form1();
f1.Show();
}
It seems to me that you have two sequences of strings: a sequence of transNumbers and a sequence of comboItems (in fact they are your transnumber_list and your combos_list, but I don't want to limit myself to the fact that they are Lists, and the names are inconsistent (the first is non-plural, the 2nd is plural?)
Anyway, you say that your sequence of transNumbers contains only unique items, but that your comboItems might contain duplicates (based on some string equality comparer)
Something like this:
IEnumerable<string> transNumbers = new string[] {"1", "2"};
IEnumerable<string> comboItems = new string[] {"A", "A", "A", "B", "A", "B"};
As a result you want something like:
TransNumber ComboItem
"1" "A"
"1" "B"
"2" "A"
"2" "B"
So you want to combine every TransNumber, with every unique comboItem.The order seems not to be important.
With LINQ This is fairly easy. We'll use Enumerable.SelectMany to combine the two sequences and we'll use Enumerable.Distinct to get rid of your duplicates
// SelectMany:
// parameter source: transNumbers
// parameter collectionSelector: comboItems without Duplicates
var transNumberCombiItemCombinations = transNumbers.SelectMany(
// collectionSelector: comboItems without duplicates
combiItems.Distinct(),
// ResultSelector, take a transNumber from the source,
// and a comboItem from collectionSelector to make a new object
(transNumber, comboItem => new
{
Column1 = transNumber,
Column2 = comboItem,
});
If you remove all comments, you'll see that it is really a small piece of code.
Distinct will remove the duplicates. If you consider "myname" and "MYNAME" to be equal, you'll need to provide an IEqualityComparer<string>, for instance StringComparer.OrdinalIgnoreCase.
SelectMany" will do your foreach inside foreach.
The resultSelector will take one transNumber and one comboItem as input to create the output you want. In this case, one object that has two properties: Column1 and Column2.
The result is an IEnumerable. All you have to do is enumerate it into a list or something and add the result to your rows collection:
dt.Rows.AddRange(transNumberCombiItemCombinations.ToList());

Sorting list with items from ListBox as Int [duplicate]

This question already has answers here:
How to convert List<string> to List<int>?
(15 answers)
Closed 5 years ago.
Explaning this WindowsFormAplication:
I have two buttons one is for inserting numbers in listbox1 with textbox and that works fine ,second button is for sorting the elements from listbox1(numbers) as int or array to listbox2.It needs to be int or array because if i sort it as string then if i have for example 3,2,10 as my elements in listbox its going to sort it as 10,2,3 because its string,
Now i have this code in my sort button where i made list from listbox elements and sorted it as string and dont know how to convert the list to array or int:
private void button2_Click(object sender, EventArgs e)
{
List<String> lista = new List<string>();
foreach (String x in listBox1.Items)
{
lista.Add(x);
}
lista.Sort();
foreach (string a in lista)
{
listBox2.Items.Add(a);
}
}
You can pass a Comparison delegate to your lista.Sort() method that will cast the items to ints and sort them by their numeric value. Like this:
lista.Sort((a, b) =>
{
return Convert.ToInt32(a).CompareTo(Convert.ToInt32(b));
});
Note this does no checking that the conversion is valid or anything like that.
I found the solution myself so this is the code:
private void button2_Click(object sender, EventArgs e)
{
List<int> lista = new List<int>();
foreach (string x in listBox1.Items)
{
lista.Add(Convert.ToInt32(x));
}
lista.Sort();
foreach (int a in lista)
{
listBox2.Items.Add(a);
}
}
I hope someone finds this helpful.
A ListBox accepts elements of any type, not just strings. So, you can add ints directly. There is no need to convert to string. You can then retrieve ints again.
However, I would store the values in a list and not in the items collection of the listbox.
private List<int> numbers = new List<int>();
private void btnAdd_Click(object sender, EventArgs e)
{
if(Int32.TryParse(TextBox1.Text, out int n)) {
numbers.Add(n);
listBox1.DataSource = null;
listBox1.DataSource = numbers;
} else {
MsgBox.Show("You must enter an integer!");
}
}
private void btnSort_Click(object sender, EventArgs e)
{
numbers.Sort();
listBox1.DataSource = null;
listBox1.DataSource = numbers;
}
Setting the DataSource of the listbox does not insert the items into the listbox, but tells the listbox to display the elements from your collection instead of its own internal collection.
If you assign the same list twice, the listbox won't notice that the contents of the list changed. Therefore, assign null first.

Return ComboBox From Function?

The below code has a list and loops through each string item in that list and adds it to a ComboBox. This functions correctly, but I am curious if there is a possible way to pass a string list and ComboBox into a function and return the ComboBox with each item in the string list being added.
Example: gets a string list, then adds each string item to the list. This is great if there's one ComboBox; but if there are 3 or more, to avoid code repetition, passing in a list and ComboBox would save code.
List<string> myList = getList();
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}
you can make method like
private void FillCombo(ComboBox myComboBox, List<string> list);
{
foreach (string listItem in myList)
{
myComboBox.Items.Add(listItem);
}
//alternatively, you can add it like fubo suggested in comment
//myComboBox.Items.AddRange(myList.ToArray());
}
and call it from somewhere in code
List<string> myList = getList();
FillCombo(this.comboBox1, myList);
FillCombo(this.comboBox2, myList);
// etc...

How to save from a listbox

I am attempting to save items from a listbox to a file; I have tried using things like
listbox.items
listbox.items.addrange
listbox.items.count
listbox.items.text (which doesn't give me an error but it also doesn't save)
Here is code:
private void button2_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, listBox1.Items.Count);
}
}
File.WriteAllText expects two items: a filepath, and the string to write (as a String):
You gave it:
ListBox.Items (a collection)
ListBox.Items.AddRange (a function)
ListBox.Items.Count (Valid, but not related to the actual items because it is just the count)
ListBox.Items.Text (what????) (this probably doesn't compile, as I'm not aware of that property)
You need to iterate through all the items, joining them all if you really want to use File.WriteAllText.
Something like:
File.WriteAllText(saveFileDialog1.FileName, String.Join(",", listBox1.Items));
//If the above doesn't do the cast implicitly, and its always better to be explicit!
File.WriteAllText(saveFileDialog1.FileName, String.Join(",", listBox1.Items.Cast<string>()));
String.Join
There are lots of other ways to generate the output of course, but the short of it is that you need to iterate each element in the Items collection and write it out to the file individually, or use a function like String.Join to do it all in one go.
You could loop through the items and create a string that contains all of them, then write that string to the file.
string itemString = "";
foreach (Item item in listbox1.Items)
{
itemString+=item.Text;
}
File.WriteAllText(saveFileDialog1.FileName, itemString);
You would probably want to add some sort of delimiter with each item, a comma, or a newline character or something so the file doesn't look like gibberish.
To save the items from listBox:
private void SaveItems()
{
using(StreamWriter sw = new StreamWriter("file.txt"))
{
for (int i = 0; i < listBox1.Items.Count; i++)
{
sw.WriteLine(listBox1.Items[i]);
}
}
}
To load the items to listBox:
private void LoadItems()
{
using(StreamReader sr = new StreamReader("file.txt"))
{
while (!sr.EndOfStream)
{
listBox1.Items.Add(sr.ReadLine());
}
}
}
If you want to store every item in a ListBox into a file, it would be best to use File.WriteAllLines(String, String[]).
File.WriteAllLines(saveFileDialog1.FileName,
listBox1.Items.OfType<ListViewItem>().Select(i => i.Text).ToArray());

Variable string editing

I have a form on which you can select multiple items to create a code.
Eg. if I clicked on "name", it would add that to the string, then if I clicked "age" it would then add that to the string, but if I unchecked "name", it would remove it from the string.
I have no idea of how to go about this. Can someone help?
Take a List<string> and add/remove items to/from the list. Once you are done, you make a call to string.Join and construct a single string from array.
List<string> items = new List<string>(); // declare globally
private void add(string item)
{
items.Add(item);
}
private void remove(string item)
{
items.Remove(item);
}
private string convertArrayToString(string delimiter, List<string> elements)
{
delimiter = (delimiter == null) ? "" : delimiter;
return string.Join(delimiter, elements.ToArray());
}
Note:
Giving a priority to List<T> over string[] would be a good decision since, here collection would be resize. Have a look at this discussion which can help you on this.
Simply use a List.
List<string> myList = new List<string>();
myList.Add("Somestring");
Then you can use the following methods:
myList.Remove or myList.RemoveAll or myList.RemoveAt and so on.
Why not using List? it allows you to add/remove elements easily?
if you click on name, just add it to the list, when you uncheck the name, remove it from the list,
after that, you can convert your list into a string and use it.
//Add string
var myList = new List<string>();
//After clicking:
myList.add(clickedElement);
//After uncheck
myList.remove(uncheckedElement);
//At the end, just convert your list to string to use it
var myString = string.Join(" ", myList.ToArray());

Categories