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;
}
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 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
I just have a question regarding C# list. I am a totally noob when it comes to programming and I'm really sorry for being a bird brainer. I am doing some practice coding and I am creating a simple program that will allow users to input names through textbox1 and then once they press the button1, the names will be stored in a List and will be output on textbox2.
I am having hard time storing the data from textbox1. Checked it online but I haven't found the right article for my concern so I'm trying my luck here.
Sorry guys, I forgot to mention I am using Winforms.
Thank you so much for the fast replies.
assuming winforms...
Drag and drop 2 lists and a button onto your designer.
drag a button onto your designer
double-click your button to automatically create an event
make a list structure somewhere inside your form to store the list
instantiate your list in the form constructor
in the button1_Click event add the text of textbox1 to the list
generate the text of 1textbox2`
here is an example
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 WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
list = new List<string>();
}
List<string> list;
private void button1_Click(object sender, EventArgs e)
{
list.Add(textBox1.Text);
string txt = "";
foreach(string s in list)
{
txt += s + " ";
}
textBox2.Text = txt;
}
}
}
Something like that ?
string name = Textbox1.Text;
ListBox1.Add(name);
If your utilizing a traditional Windows Form Application; I'm not sure you meant to store the data in another Text Box. But a List Box may be more along your goal.
Drag the following: Textbox, Second Textbox, Listbox, and Button from the toolbox to your Form.
Adjust them however you would like, treat them like a canvas for a painting.
Once it appears to be configured how you would like double click the Button.
At this point Visual Studio will leave Designer View and go into Code View. So you'll be able to see the code. It will automatically place you in the Button code block.
These blocks are quite important, as you progress you'll notice how C# is structured.
private void button1_click(object sender, EventArgs e)
{
// Logic to add will go in here.
}
What does this mean?
Private : Is the modifier, it means it is restricted to this class.
Void: Means it isn't asking for a return type.
button1_click: That is the name of the button, you can change that within it's Properties. It's good practice to name the component infront so you know what your working with.
What that entire block is, is an Event. So when it is clicked it will perform an action. That is what it means; so this is where your goal is implemented:
private void btnAddToList_Click(object sender, EventArgs e)
{
// Test to ensure it isn't null.
if(txtAddText.Text != String.EmptyOrNull)
{
// Declare a variable with the initial textbox value.
string txtVar = txtAddText.Text;
// Has the second textbox inherit value from other Textbox.
txtNewText = txtVar
// Now Add it to a Listbox.
lstContainer.Items.Add(txtAddText.Text + DateTime.Now());
}
else
{
// Null or Empty Character, Error Message.
MessageBox.Show("Invalid Entry, please enter a valid entry");
}
}
That will provide the fundamental knowledge, but as you can see from your other examples they do it differently. You'll notice that bugs can exist in such logic if you aren't careful. Which you'll learn to identify based on the structure you configure.
Hopefully this is helpful, and it looks like a lot of others did some terrific post for you as well.
Happy coding.
You could use something simple as this:
private void button1_Click_1(object sender, EventArgs e)
{
string[] names = textBox1.Text.Split(new string[] { " ", Environment.NewLine, "," }, StringSplitOptions.RemoveEmptyEntries);
//you can add more parameters for splitting the string
textBox2.Text = string.Join(",", names);
//you can replace the comma with something more suitable for you
}
The first line splits the string that you entered in the textBox1 (hence names separated by newlines, blank characters or commas) into array of string (instead of list that you requested) and the second line joins the strings into one big string of names separated by commas and puts it into the textBox2
This is very simple.
List<string> mylist=new List<string>();
mylist.Add(textbox1.Text);
textbox2.Text=mylist[mylist.Count - 1]
First you create a list of string objects.
Then add the text from textbox1 to the end of the list.
Then get the last element you added from the list by getting the length of the list and subtracting 1 since in C# collections are 0 based and the first element is [0] and not [1].
Within the button1 click listener (if you don't have this hook go into the GUI builder view and double click on the button, it will automatically create and register the listener for you), add the following code;
textbox2.Text = textbox1.Text; // set tb2 = tb1
textbox1.Text = System.String.Empty; // clear tb1
Now, in your post you say store the data in a list, but you don't specify how the user is to input that data so it's hard to give you a specific answer. If the names are say separated by commas to get an array with all the names you could simply do;
string[] names = textbox1.Text.Split(',');
However, from your post it doesn't seem you want to store the data in a list at all. If you just want the input in textbox1 to be displayed in textbox2 upon clicking the input button then use use the first code snippet. If you go the second route, you'll have to convert the array back into a single string. This can be done easily with a for loop.
string result = System.String.Empty;
for (int i = 0; i < names.Length; i++)
result = result + names[i] + " ";
To make textbox2 display what's in textbox1 and display the number of names;
textbox2.Text = textbox1.Text; // set tb2 = tb1
string[] names = textbox1.Text.Split(','); // i use a comma but use whatever
// separates the names might just want ' ' for whitespace
textbox1.Text = System.String.Empty; // clear tb1
MessageBox.Show("You entered " + names.Count.ToString() + " names."); // show the names count
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 ShowAllSaveNameAndCountApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> ourList=new List<string>();
string txt =" ";
private void buttonSave_Click(object sender, EventArgs e)
{
ourList.Add(textBoxEntryName.Text);
foreach (string s in ourList)
{
txt+= s+ "\n ";
}
textBoxEntryName.Clear();
ourList.Clear();
}
private void buttonShowAllName_Click(object sender, EventArgs e)
{
textBoxShowName.Text = txt;
}
}
}
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";
Really new and learning C# and following along some training video from PluralSight. Great videos, except you cannot ask questions, of course and I am not understanding why what I am seeing is different that what his screen is displaying even though I typed exactly what he has.
Textbox is named "Output". Initially, the actions were directly in the MainWindow constructor (which he explained is not good practice, so we moved it. Initially, this worked as it should:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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 WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Employee e1 = new Employee();
e1.Name = "Mike";
Employee e2 = new Employee();
e2.Name = "Miller";
Output.Text = e1.Name + " " + e2.Name;
}
}
}
This would display "Mike Miller" in the TextBlock.
However, when we moved it to this, all it says for the text is "TextBlock"
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Employee e1 = new Employee();
e1.Name = "Mike";
Employee e2 = new Employee();
e2.Name = "Miller";
Output.Text = e1.Name.Length + " " + e2.Name.Length;
}
}
}
Am I missing something simple here?
Thanks!
As Nico Schertler stated, verify that you subscribed to Loaded event of Window:
<Window ... Loaded="MainWindow_Loaded">
...
</Window>
In first case your code runs, because constructor of Window is called when Window is created. In second case, event handler is not called by default. You should subscribe to this event.
If you take the .Length off the two strings, it should work. You're concatenating integers with a string using "+" and that doesn't work so well.
Output.Text = e1.Name + " " + e2.Name;
Answer is very certain from your question:
Firstly if you are expecting output to be "Mike Miler" change your code to the one which is posted by Bravan.
Secondly you need to add Loaded event to your MainWindow declaration in XAML.
other than that nothings wrong there...!!!
Happy Coding...!! :)