Newb here,
I'm currently working on a form which has a combo box, which will show several Charlie Brown TV specials which you can click on to select and see a description of, rating, runtime, etc. I'm close but I'm not there in terms of populating the combo box and i'm hoping for some help and guidance. I have looked at several things others have done but i'm not knowledgeable enough to deduce the answers from what i've been able to see so far.
Right now i'm trying too:
1. get the listings from your load method
2. loop through them
3. Access my combo box to populate the box with the times from the listing.
Form1.cs
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;
using System.Globalization;//Used for Sting.ToUpperCase...
using System.Threading;
using System.Threading.Tasks;// Needed for Streaming...
using System.IO;// Needed for Streaming...
namespace a100___GUI___VideoStoreSelections
{
public partial class FormMovieLookUp : Form
{
private const String FILE_NAME = "txt_movieDescriptions.txt";//connect to text file in debug
private List<Listing> films { get; set; }
public FormMovieLookUp()
{
InitializeComponent();
}
private void cmbMovieListingBox_SelectedIndexChanged(object sender, EventArgs e)
{
txtTitleBox.Text = cmbMovieListingBox.SelectedItem.ToString();
}
//ToolBox -- my program specific tools
public List<Listing> LoadListings()//load movie descriptions as list
{
StreamReader fileIn = new StreamReader(FILE_NAME);
List<Listing> entries = new List<Listing>();
//loop through every line of the file
while (!fileIn.EndOfStream)
{
String line = fileIn.ReadLine();
String[] pieces = line.Split(':');
if (pieces.Length < 4) continue;//error handling - set to length of text items
Listing myListing = new Listing(pieces[0], pieces[1], pieces[2], pieces[3]);
entries.Add(myListing);
}
fileIn.Close();
return entries;
}
private void FormMovieLookUp_Load_1(object sender, EventArgs e)
{
films = LoadListings();
foreach (Listing film in films)
{
Console.WriteLine(film);
cmbMovieListingBox.Items.Add(film.GetFilmTitle());
}
}
}
}
Listing.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace a100___GUI___VideoStoreSelections
{
public class Listing
{
private String filmTitle;
private String description;
private String filmRunTime;
private String filmRating;
public Listing(String filmTitle, String description, String filmRunTime, String filmRating)
{
this.filmTitle = filmTitle;
this.description = description;
this.filmRunTime = filmRunTime;
this.filmRating = filmRating;
}
public String GetFilmTitle() { return filmTitle; }
public String GetDescription() { return description; }
public String GetFilmRunTime() { return filmRunTime; }
public String GetFilmRating() { return filmRating; }
}
}
So this is what i'm trying to do to populate my combo box. Any help is thankfully received.
I would hold List<Listing> at the class level so you can access it when a user clicks on it. I would also throw this on it's own thread and not directly in the Load event. If it's a long process you will hang the ui.
private List<Listing> films { get; set; }
Load
films = LoadListings();
foreach (Listing film in films)
{
cmbMovieListingBox.Items.Add(film.GetFilmTitle());
}
When the user selects the item
Listing film = films.Where(f => f.GetFilmTitle().Equals(cmbMovieListingBox.SelectedValue)).FistOrDefault();
if (film != null)
{
//do work
}
if you are asking what i think you are asking, you need something like this in your form load:
foreach(Listing listing in LoadListings()){
cmbMovieListingBox.Items.Add(listing.GetFilmTitle());
}
Remove the {get; set;} from the list declaration. It's not needed there.
Define your class like this:
public class Listing
{
private String filmTitle {get; set;}
private String description {get; set;};
…
}
On the form load event set the ComboBox DisplayMember and ValueMember to "filmTitle"
cmbMovieListingBox.DisplayMember = "filmTitle";
cmbMovieListingBox.ValueMember = "filmTitle"
Finally, you must set the DataSource of the ComboBox to the list
cmbMovieListingBox.DataSource = films;
And there you have it. The rest of your code should function now.
There's one issue with visual controls updating (such as ComboBox etc): you'd rather prevent them from re-painting at each data change (at each item addition in your case):
cmbMovieListingBox.BeginUpdate(); // <- Stop painting
try {
// Adding new items into the cmbMovieListingBox
foreach(var item in LoadListings())
cmbMovieListingBox.Items.Add(item.GetFilmTitle());
finally {
cmbMovieListingBox.EndUpdate(); // <- Finally, repaint if required
}
A line of the code of Tsukasa doesn't work because it is written FistOrDefault() instead of FirstOrDefault()
Listing film = films.Where(f => f.GetFilmTitle().Equals(cmbMovieListingBox.SelectedValue)).**First**OrDefault();
Sorry I don't have enough point to just add a comment...
Maybe it will help somebody. But in my situation I had to use cmbMovieListingBox.Text instead of cmbMovieListingBox.SelectedValue (like #Tsukasa example):
Listing film = films.Where(f => f.GetFilmTitle().Equals(cmbMovieListingBox.Text)).FirstOrDefault();
if (film != null)
{
//do work
}
And also FirstOrDefault() instead of FistOrDefault().
Hope it helps to someone
that what i did to my Code
int Count;
foreach(String i in Languages)
{
LangComboBox.Items.Add(Languages[Count]);
Count++;
}
Related
When I am trying to filter records that match any item in the search list then it's not returning me anything. please see code
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Test {
// Main Method
public static void Main(String[] args)
{
List<String> searchlist = new List<String>();
searchlist.Add("Mang");
searchlist.Add("Apple");
List<String> firstlist = new List<String>();
firstlist.Add("Mango");
firstlist.Add("Apple");
firstlist.Add("Orange");
firstlist.Add("Grapes");
test1 obj = new test1();
obj.stringList = firstlist;
Console.Write(obj.stringList.Where(x=> searchlist.Contains(x)).Count());
}
public class test1
{
public string id { get; set; }
public string name { get; set; }
public List<String> stringList { get; set; }
}
}
In the above example, if I will pass a full string like "Mango" then it will return the result but if I try to search only "Mang" (partial words) then it's not working.
The reason is that when using Contains() on a collection, it results in comparing its items. So you are asking whether "Mang" == "Mango"
As it was stated here in another answer, you want to ensure that strings are compared using contains, but it is important to choose which string we apply a Contains to
var result = obj.stringList.Where(item => searchlist.Any(searchString => item.Contains(searchString))).Count();
Try this
Console.Write(obj.stringList.Where(x => searchlist.Any(list => x.Contains(list))).Count());
In my C# / WPF application, I have a ListView control, which I populate as follows:
private void Load()
{
DbSet<recordHistory> recordHistory = _db.recordHistories;
var query = from cbHistory in recordHistory
orderby cbHistory.id descending
select new { cbHistory.id, cbHistory.Content, cbHistory.Size, cbHistory.DateAdded };
crRecordHistoryList.ItemsSource = query.ToList();
}
The above works as expected. My ListView control is populated with all the saved records from a SQL database.
When I start debugging the application, it executes as expected. However, when I select one of the ListView items (regardless of which item I select) and click on the Remove button, only the first record gets removed from the database and the ListView control.
Intended behavior is for the selected record to be removed from the database & the listview control...
My Remove method
private void Button_Remove_Click(object sender, RoutedEventArgs e)
{
foreach (var record in _db.recordHistories.Local.ToList())
{
Console.WriteLine("Removing Record Id:" + record.id);
_db.recordHistories.Remove(record);
}
_db.SaveChanges();
this.crRecordHistoryList.Items.Refresh();
this.Load();
}
Furthermore, all subsequent item selection and clicking on the remove button result in nothing being removed from database/listview control)
I have also tried the following (just to get the ID), within the Remove method:
Console.WriteLine("Removing Record Id:" + (crRecordHistoryList.SelectedItem as recordHistory).id);
in which case, I get:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
My recordHistory class (auto generated)
using System;
using System.Collections.Generic;
public partial class recordHistory
{
public int id { get; set; }
public string Content { get; set; }
public string Size { get; set; }
public Nullable<int> DateAdded { get; set; }
}
EDIT: I have figured out why it only removes the first record and then nothing else happens (no matter which item is selected)... it is because instead of getting the record from Local (in my foreach statement), I should simply have the following --- which was my initial attempt, trying to get the ID outputted to Console:
private void Button_Remove_Click(object sender, RoutedEventArgs e)
{
recordHistory testRecord = new recordHistory();
testRecord.id = (recordHistory)crRecordHistoryList.SelectedItem;
_db.recordHistories.Attach(testRecord);
_db.recordHistories.Remove(testRecord);
_db.SaveChanges();
this.crRecordHistoryList.Items.Refresh();
this.Load();
}
However, the following line
testRecord.id = (recordHistory)crRecordHistoryList.SelectedItem;
is throwing an error:
Cannot implicitly convert type 'recordHistory' to 'int'
By the way: the above would work perfectly, if I replace the 2nd line with: testRecord.id = 85; for example.
As such, I have tried changing the aforementioned line to the following, to no avail:
testRecord.id = System.Convert.ToInt32(crRecordHistoryList.SelectedItem);
Any ideas how I can remove the selected record?
Kudos to #pinkfloydx33 for pointing me in the right direction. Per his comment, I ventured onto further-research-rabbit-hole which eventually led to me creating a DTO class and modified my Load and Remove methods as follows--
Load method
private void Load()
{
List<HistoryRecordsDTO> records = (from record in _db.recordHistories
orderby record.id descending
select new HistoryRecordsDTO
{
id = record.id,
Content = record.Content,
Size = record.Size,
DateAdded = record.DateAdded
}).ToList();
crRecordHistoryList.ItemsSource = records;
}
Remove method
private void Button_Remove_Click(object sender, RoutedEventArgs e)
{
recordHistory record = new recordHistory();
record.id = (crRecordHistoryList.SelectedItem as HistoryRecordsDTO).id;
_db.recordHistories.Attach(record);
_db.recordHistories.Remove(record);
_db.SaveChanges();
this.crRecordHistoryList.Items.Refresh();
this.Load();
}
And, my DTO class - HistoryRecordsDTO
public class HistoryRecordsDTO
{
public int id { get; set; }
public string Content { get; set; }
public string Size { get; set; }
public Nullable<int> DateAdded { get; set; }
}
Doing the above solved my problem of removing a selected ListView item.
As being a C#/WPF newbie, I am certain that there are much nicer/optimal/better in general ways to do this... I look forward to other answers and learn from it.
I have a dictionary that is declared as a property so that I can access it within other functions and event handlers but seeing as I'm new to c# I can't figure out how to do this properly
Declaring the dictionary
Dictionary<string, int> occurrenceDictionary { get; set; }
I have two functions. The first functionOne turns a list of words into a dictionary<string, int> where string is a word, and int is the number of times that word occurs in the list.
public string functionOne(List<string> myList)
{
foreach (string item in myList)
{
if (!occurrenceDictionary.ContainsKey(item))
{
occurrenceDictionary.Add(item, 1);
}
else
{
occurrenceDictionary[item]++;
}
}
return maxKey;
}
The second function compares user input wordSearch.Text to this dictionary occurenceDictionary and if they match, then the user will be told how many times this word occurs (the keys are the words, the values are the amount of occurrences).
public int word_search(Dictionary<string, int> myDict)
{
if(myDict != null)
{
if (myDict.ContainsKey(wordSearch.Text))
{
...
}
else
{
...
}
}
else
{
...
}
}
Now I have an event listener that is waiting for the user to click the Search button. This is the part I'm having the most trouble with, I don't know how to call my word_search function properly inside the event handler, because the way I have it at the moment, I always get a NullReferenceException and it says to fix it I have to add
if(occurencesDictionary != null) ... But adding this to functionOne doesn't make sense to me because I want the items to be added to the dictionary regardless of whether its empty or not because functionOne is populating the dictionary. So I'm not sure how else to get around this problem
If anyone could tell me what I'm doing wrong or perhaps show me an easier method that would be helpful
... But adding this to functionOne doesn't make sense to me because I want the items to be added to the dictionary regardless of whether its empty or not because functionOne is populating the dictionary.
occurencesDictionary is not empty, It's not even initialized.
You will have do first initialize it before using it.
Either you do it in the constructor or by property initializer:
Dictionary<string, int> occurrenceDictionary { get; set; } = new Dictionary<string, int>();
You only declared but never initialized (with new) your hash variable so it is always null.
You need public Dictionary occurrenceDictionary = new Dictionary();
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Dictionary<string, int> occurrenceDictionary = new Dictionary<string, int>();
public string functionOne(List<string> myList)
{
string maxKey = "";
foreach (string item in myList)
{
if (!occurrenceDictionary.ContainsKey(item))
{
occurrenceDictionary.Add(item, 1);
}
else
{
occurrenceDictionary[item]++;
}
}
return maxKey;
}
public int word_search(Dictionary<string, int> myDict)
{
if(myDict != null)
{
if (myDict.ContainsKey(wordSearch.Text))
{
}
else
{
}
}
else
{
}
return 1;
}
private void buttonSearch_Click(object sender, EventArgs e)
{
occurrenceDictionary.Add("hello", 1);
}
}
}
I'd like to have it so that a list of names gets split, and then the first and last name gets split, so that each person's pair of first and last name is operated on.
So, I have a list of names seperated by ';' that gets split into an array
In another class, I get this array, and using foreach, I split the char in the array by ',', giving me the first and last name.
I am wondering how I can call this last operation into the main so that my first and last names can eventually all each have their own operations carried out on.
Thanks
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
pairInName funOperations = new pairInName();
//I'd like to have the method from 'pairInName' to have the split list ',' (from the split list ';')
//How can I run it so that it carries out the operation in my main()?
//eventually, I'd like it so that it carries out a method in my main for each pair of first and last name, for each name in the list
Console.WriteLine();
Console.ReadLine();
}
}
public class namesList
{
public static string listOfNames = (
"Tyrion,Lannister;" +
"Euron,GreyJoy;" +
"Davos,Seaworth;" +
"Lord,Varys;" +
"Samwell,Tarly;"
);
public static string[] splitListOfNames = listOfNames.Split(';');
}
public class pairInName
{
static void myOperations()
{
foreach (string champName in namesList.splitListOfNames)
{
string[] splitChampName = champName.Split(',');
}
}
}
}
The method marked as static, if you will also change the access modifier from private (default when not filling any modifier) to public, then you can access it directly.
pairInName.myOperations();
Remark: your complete structure isn't very OOP, you should consider refactor the design using classes and methods which more closer to the actual nature of the data context.
Create a Character entity will be a good start
public class Character
{
public string FirstName { get; private set; }
public string LastName { get; private set; }
public Character(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
Mark your myOperations() as public , then you can use "pairInName.myOperations();" from main method .
public class pairInName
{
string[] splitChampName;
public static void myOperations()
{
foreach (string champName in namesList.splitListOfNames)
{
splitChampName = champName.Split(',');
}
}
public string[] getSplitResult
{
get { return splitChampName; }
}
}
i need to extend the DropDownList For adding toolTip For DropDown Item On mouseOver.
If(Dropdown size is samller than Dropdownlist item then it will be useful for seeing the item as tool tip)
For that i came to know, We need to create ServerControl project in VS2008 but i dont know how to add a property like ItemToolTip
which need to be worked as (DataTextField, DataValueField in drop down list) in that class .
tell me any link for ServerControl project sample which resembles my requirement.
I tried using below code but dropdown property itself not working..
namespace DropDownItemToolTip
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ServerControl1 : System.Web.UI.WebControls.DropDownList
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text1
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(Text1);
}
}
}
Send me any sample project link, which done like this..
Why you want to extend the Dropdownlist? Try adding a Title tag will work right?
Try this code
<select>
<option title="this is a long text">Long text</option>
</select>
It will show a this is a long text tooltip on mouseover.
Try this:
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Foo
{
[ToolboxData("<{0}:DDL runat=\"server\" />")]
public class DDL : DropDownList
{
[Category("Data"), DefaultValue("")]
public string DataToolTipField
{
get { return (string)(ViewState["DataToolTipField"] ?? string.Empty); }
set { ViewState["DataToolTipField"] = value; }
}
protected override void PerformDataBinding(IEnumerable dataSource)
{
base.PerformDataBinding(dataSource);
string dataToolTipField = this.DataToolTipField;
if (!string.IsNullOrEmpty(dataToolTipField))
{
IEnumerator enumerator = dataSource.GetEnumerator();
for (int i = 0; enumerator.MoveNext(); i++)
{
this.Items[i].Attributes.Add("title", (string)DataBinder.GetPropertyValue(enumerator.Current, dataToolTipField));
}
}
}
}
}