C# How to concatenate path and variable - c#

I want to display a different photo according to the text on the listBox. It will be about 1000 photos +.
The listbox.text will be the name of the picture(1, 2 ,3 etc).
I have no idea how to do that.
pictureBox1.Image = WindowsFormsApplication1.Properties.Resources.(listBox2.Text);
Thanks for any help!

I guess this is what you want, you should get selected Item's text:
var imgName = listBox2.SelectedItem.ToString();
pictureBox1.Image = Resources.ResourceManager.GetObject(imgName) as Bitmap;

A very handy thing to do with list boxes is to add objects to them. The listbox displays the object's ToString() as the name of the object and you can then get the object directly using the SelectedItem property. Something like this would do what you need:
namespace showimage
{
public partial class Form1 : Form
{
private List<ImagePicker> image_list;
public Form1()
{
InitializeComponent();
image_list = new List<ImagePicker>();
// Add the images - creating an ImagePicker object per file
image_list.Add(new ImagePicker("Photo1", "photo1.jpg"));
image_list.Add(new ImagePicker("Photo2", "photo2.jpg"));
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.AddRange(image_list.ToArray());
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ImagePicker picked_image = (ImagePicker)listBox1.SelectedItem;
pictureBox1.Load(picked_image.filename);
}
}
public class ImagePicker
{
private string _name;
private string _filename;
public string filename
{
get
{
return _filename;
}
}
public ImagePicker(string name, string filename)
{
_name = name;
_filename = filename;
}
public override string ToString()
{
return _name;
}
}
}

Related

How to add to a List and display images from Resource File

I am creating a BlackJack game and I'm currently having a problem displaying the card image needed on my list.
I have added all 52 card to my resource file and I can't seem to have them displayed in a PictureBox.
Am I going about the right way?
My Card class:
internal class Card
{
public int Value { get; set; }
public string Name { get; set; }
public string Image { get; set; }
public Card(int value, string name, string image)
{
Value = value;
Name = name;
Image = image;
}
}
Main Form:
public partial class Form1 : Form
{
static List<Card> myListOfCards = new List<Card>();
static List<Card> dealersHand = new List<Card>();
static List<Card> playersHand = new List<Card>();
private void startButton_Click(object sender, EventArgs e)
{
//Clubs
myListOfCards.Add(new Card(2, "Two of Clubs", "Resources._2C.png"));
}
}
I've spotted a potential issue. Your code uses "Resources._2C.png" as a literal, and the Card class deals with it as a string. One way or another an Image must be retrieved from the resources of the Assembly and I don't see any code that does that.
Try this change:
class Card
{
// METHOD 1
// CTor with Image
public Card(int value, string name, Image image)
{
Value = value;
Name = name;
Image = image;
}
// METHOD 2
// CTor with string
// The `BuildAction` property for the image files must
// be set to `EmbeddedResource` for this version to work.
public Card(int value, string name, string resource)
{
Value = value;
Name = name;
Image = Image.FromStream(
typeof(Card)
.Assembly
.GetManifestResourceStream(resource));
}
public int Value { get; }
public string Name { get; }
// Try making this an Image
public Image Image { get; }
}
In the MainForm:
The image can either be read from the Resource file by removing the quotes and the extension:
// METHOD 1
private void buttonCard1_Click(object sender, EventArgs e)
{
var card = new Card(1, "AceOfDiamonds", Resources.AceOfDiamonds);
pictureBox1.Image = card.Image;
}
OR if the string is used, it must be fully qualified:
// METHOD 2
private void buttonCard2_Click(object sender, EventArgs e)
{
// Get full names of available resources
Debug.WriteLine(
string.Join(
Environment.NewLine,
typeof(MainForm).Assembly.GetManifestResourceNames()));
var card = new Card(2, "EightOfSpades", "resources.Images.EightOfSpades.png");
pictureBox1.Image = card.Image;
}
Gets this in the PictureBox:
FYI: Here are the available embedded resources listed by the Debug.WriteLine:

How we can refresh items text in ListBox without reinserting it?

I have the class TestClass that has ToString overriden (it returns Name field).
I have instances of TestClass added into ListBox and at certain point I need to change Name of one of this instances, how then I can refresh it's text in ListBox?
using System;
using System.Windows.Forms;
namespace TestListBox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add(new TestClass("asd"));
listBox1.Items.Add(new TestClass("dsa"));
listBox1.Items.Add(new TestClass("wqe"));
listBox1.Items.Add(new TestClass("ewq"));
}
private void button1_Click(object sender, EventArgs e)
{
((TestClass)listBox1.Items[0]).Name = "123";
listBox1.Refresh(); // doesn't help
listBox1.Update(); // same of course
}
}
public class TestClass
{
public string Name;
public TestClass(string name)
{
this.Name = name;
}
public override string ToString()
{
return this.Name;
}
}
}
try
listBox1.Items[0] = listBox1.Items[0];
I have encountered this same issue and tried all sorts of different ways to tr y to get the displayed text of an item to actually reflect the underlying item value.
After going through all the available properties I found this to be the simplest.
lbGroupList.DrawMode = DrawMode.OwnerDrawFixed;
lbGroupList.DrawMode = DrawMode.Normal;
It triggers the appropriate events within the control to update the displayed text.
Your Testclass needs to implement INotifyPropertyChanged
public class TestClass : INotifyPropertyChanged
{
string _name;
public string Name
{
get { return _name;}
set
{
_name = value;
_notifyPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void _notifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public TestClass(string name)
{
this.Name = name;
}
public override string ToString()
{
return this.Name;
}
}
However this only works if you use Columns that do not rely on the ToString() but bind the property Name
This can be done by altering your code:
somewhere in class declare
BindingList<TestClass> _dataSource = new BindingList<TestClass>();
In initializeComponent write
listBox1.DataSource = _dataSource;
Then do all operations on _dataSource instead of Listbox.
You could use a BindingList:
items = new BindingList<TestClass>( );
listBox1.DataSource = items;
listBox1.DisplayMember = "_Name";
Then to refresh the list call:
items.ResetBindings( );
edit: Also don't forget to create a get Property for Name
public string _Name
{
get { return Name; }
set { Name= value; }
}
I use the following code:
public static void RefreshItemAt (ListBox listBox, int itemIndex)
{
if (itemIndex >= 0)
{
Rectangle itemRect = listBox.GetItemRectangle(itemIndex);
listBox.Invalidate(itemRect);
listBox.Update();
}
}

Get-Set returning null when accessed by a button

I'm probably missing something simple, but have been messing with this for a few hours and I cannot get the method to return something not null. When I'm stepping over the process, getDir1 will take the value of the class "swSheetFormatCycle.Form1.FolderUpdate", but getDir1.SwDir remains null so swDir remains null. Will the button method not set swDir or swTemplate the way I'm doing it?
// Get-Set Class
public class FolderUpdate
{
private string swDir;
public string SwDir
{
get {return swDir;}
set {swDir = value;}
}
private string swTemplate;
public string SwTemplate
{
get {return swTemplate;}
set {swTemplate = value;}
}
}
private void btnTemBrow_Click(object sender, EventArgs e)
{
OpenFileDialog tempBrowse = new OpenFileDialog();
DialogResult result = tempBrowse.ShowDialog();
string tempText = tempBrowse.FileName;
txtTemp.Text = tempText;
// Setting the template field
FolderUpdate temUpd = new FolderUpdate();
temUpd.SwTemplate = tempText;
}
private void btnDirBrow_Click(object sender, EventArgs e)
{
FolderBrowserDialog dirBrowse = new FolderBrowserDialog();
DialogResult result = dirBrowse.ShowDialog();
string dirText = dirBrowse.SelectedPath;
txtDir.Text = dirText;
// Setting the directory field
FolderUpdate dirUpd = new FolderUpdate();
dirUpd.SwDir = dirText;
}
// Get the directory set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir1 = new swSheetFormatCycle.Form1.FolderUpdate();
string swDir = getDir1.SwDir;
// Get the template set by the button method
swSheetFormatCycle.Form1.FolderUpdate getDir2 = new swSheetFormatCycle.Form1.FolderUpdate();
string swTemplate = getDir2.SwTemplate;
Your button events are creating new instances of your FolderUpdate class and then are not doing anything with the object and it is abandoned at the end of the method call.
your "// Get the directory set by the button method" code
is also creating new instances so they will also be null
Attach the FolderUpdate instance to the form itself so that you can reference it.
public class FolderUpdate
{
....
}
public FolderUpdate Folders { get; set; }
private void btnTemBrow_Click(object sender, EventArgs e)
{
...
Folders.SwTemplate = tempText;
}
private void btnDirBrow_Click(object sender, EventArgs e)
{
...
Folders.SwDir = dirText;
}
// Then when you are reading them
var folders = swSheetFormatCycle.Form1.Folders;
string swDir = folders.SwDir;
string swTemplate = folders.SwTemplate;

List Box with BindingSource containing objects not showing displayName C#

I have found many answered questions on here explaining how to do this when the objects are created as part of the data source but my list box is just displaying "SharePointXMLBuilder.Farm" (Namespace.class) and not the selected DisplayName?
I dont know what I am doing wrong can anyone help please.
I have a list box with a data source as a databinding control and I am adding my created objects(Farm) to the databinding(farmListBindingSource) which all works fine, I just cant get the list to show the property I want it to.
Form: (loads another form takes input and returns to create object from Farm class)
private void CreateNewFarm_Click(object sender, EventArgs e)
{
FarmInput input = new FarmInput();
input.ShowDialog();
Farm nFarm = new Farm();
nFarm.location = input.inputLocation.ToString();
nFarm.identifier = input.inputType.ToString();
nFarm.environment = input.inputEnvironment.ToString();
this.farmListBindingSource.Add(nFarm);
this.testReturnTextBox.Text = nFarm.friendlyName;
}
private void MainForm_Load(object sender, EventArgs e)
{
this.FarmListBox.DisplayMember = "friendlyName";
this.testReturnTextBox.Text = "Form Loaded....";
}
Class:
namespace SharePointXMLBuilder
{
class Farm
{
private string farmLocation;
private string farmIdentifier;
private string farmEnvironment;
private string farmFriendlyName;
//private List<Server> farmServers;
//properties
public string friendlyName
{
get { return farmFriendlyName; }
set { farmFriendlyName = value; }
}
public string location
{
get { return farmLocation;}
set { farmLocation = value; this.buildFriendlyName(); }
}
public string identifier
{
get { return farmIdentifier; }
set { farmIdentifier = value; this.buildFriendlyName(); }
}
public string environment
{
get { return farmEnvironment; }
set { farmEnvironment = value; this.buildFriendlyName(); }
}
//constructor
public Farm()
{
}
//methods
public void AddServer(string s)
{
Server nServer = new Server(s);
// farmServers.Add(nServer);
}
public void buildFriendlyName()
{
this.friendlyName = this.location + " " + this.identifier + " " + this.environment;
}
}
}
Maybe you are not calling this function: buildFriendlyName() for each object in the list prior to binding?
In your buildfriendlyname() method set your private string farmFriendlyName insted of setting the property value friendlyname
Ok, so I tried to manually add DisplayMember in the designer and it wouldn't hold the value, as soon as I removed the DataSource it allowed DisplayMember to be populated so I changed the CreateNewFarm_Click to add the object to farmListBox.Items and when I re-ran the code it was fine.
It appears that you cannot use DisplayMember if you are pulling the objects from a DataSource.

How to set the values of private members using public property?

This is my class:
class EmpDetails
{
private string _EmpName;
private int _EmpID;
private string _EmpDepartment;
private string _EmpPosition;
public string EmpName
{
get
{
return _EmpName;
}
set
{
_EmpName = value;
}
}
public int EmpID
{
get
{
return _EmpID;
}
set
{
_EmpID = value;
}
}
public string EmpDepartment
{
get
{
return _EmpDepartment;
}
set
{
_EmpDepartment = value;
}
}
public string EmpPosition
{
get
{
return _EmpPosition;
}
set
{
_EmpPosition = value;
}
}
}
}
Following is my form:
public partial class Form1 : Form
{
EmpDetails d = new EmpDetails();
public Form1()
{
InitializeComponent();
}
private void btnSet_Click(object sender, EventArgs e)
{
d.EmpName = txtName.Text;
d.EmpID = Convert.ToInt32(txtID.Text);
d.EmpDepartment = txtDepartment.Text;
d.EmpPosition = txtPosition.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtName.Clear();
txtID.Clear();
txtDepartment.Clear();
txtPosition.Clear();
}
private void btnGet_Click(object sender, EventArgs e)
{
txtName.Text = d.EmpName;
txtID.Text = Convert.ToString(d.EmpID);
txtDepartment.Text = d.EmpDepartment;
txtPosition.Text = d.EmpPosition;
}
}
}
I am setting the values using text boxes in form so that the values go
in to properties I have created in class.
I'm getting error like: EncapsulationAssignmentCSharp.EmpDetails
does not contain a definition for GetEmpName and no extension
method GetEmpName accepting a first argument of type
EncapsulationAssignmentCSharp.EmpDetails could be found (are you
missing a using directive or an assembly reference?
I am guessing that I have to create a constructor with parameters and
set the values using keyword this, but I'm not sure how to pass the
values to the constructor. Please help me I am not very good with
programming.
Debug and run the code and check whether your code is calling GetEmpName

Categories

Resources