In Visual Studio I have one ComboBox where I enter five items manually. (products) Also TextBox where I must write automatically the prices.
In array I save prices of these products and names:
string [] prodmas = new string[5];
prodmas[0] = "თევზი";
prodmas[1] = "პური";
prodmas[2] = "ყავა";
prodmas[3] = "შაქარი";
prodmas[4] = "წვენი";
double[] fasmas = new double[5];
fasmas[0] = 1.2;
fasmas[1] = 2;
fasmas[2] = 2.4;
fasmas[3] = 1.3;
fasmas[4] = 2.5;
How to do when I select item 1 in ComboBox, TextBox must show the item 1 price (1.2); when I select item3 TextBox must show the item 3 price (2.4)
private void produqcia_SelectedIndexChanged(object sender, EventArgs e)
{
.......
}
FULL CODE
string [] prodmas = new string[5];
double[] fasmas = new double[5];
void masivebi()
{
prodmas[0] = "თევზი";
prodmas[1] = "პური";
prodmas[2] = "ყავა";
prodmas[3] = "შაქარი";
prodmas[4] = "წვენი";
fasmas[0] = 1.2;
fasmas[1] = 2;
fasmas[2] = 2.4;
fasmas[3] = 1.3;
fasmas[4] = 2.5;
}
private void produqcia_SelectedIndexChanged(object sender, EventArgs e)
{
int index = produqcia.SelectedIndex;
fasi.Text = String.Format("The item {0} price {1}", index + 1, fasmas[index].ToString());
}
private void Form1_Load(object sender, EventArgs e)
{
produqcia.DataSource = prodmas;
}
}
In form constructor or elsewhere:
comboBox1.DataSource = prodmas;
Selection event:
private void produqcia_SelectedIndexChanged(object sender, EventArgs e)
{
int index = comboBox1.SelectedIndex;
textBox1.Text = String.Format("The item {0} price {1}", index + 1, fasmas[index].ToString());
}
But this is not really good approach, better create object holding two of your values and bind it to combobox. Then cast selected item to your object and get needed value.
Related
I wrote a program with C #
I have a combo box whose items are Binding from the database.I use AutoCompleteMode and AutoCompleteSource to search the combo box.But only when filtering does it find words whose first letter is the same as the input letter.While I need All items that contain these letters displayed.Is there a solution to this problem?
maybe this helps
// Example data
string[] data = new string[] {
"Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
"Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
"Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
"Adams"
};
public Form1()
{
InitializeComponent();
}
private void comboBox1_TextChanged(object sender, EventArgs e)
{
HandleTextChanged();
}
// Handle Text Box that you Fill
private void HandleTextChanged()
{
var txt = comboBox1.Text;
var list = from d in data
where d.Tolower().Contains(comboBox1.Text.ToLower())
select d;
if (list.Count() > 0)
{
comboBox1.DataSource = list.ToList();
//comboBox1.SelectedIndex = 0;
var sText = comboBox1.Items[0].ToString();
comboBox1.SelectionStart = txt.Length;
comboBox1.SelectionLength = sText.Length - txt.Length;
comboBox1.DroppedDown = true;
return;
}
else
{
comboBox1.DroppedDown = false;
comboBox1.SelectionStart = txt.Length;
}
}
I am stuck with the project C# and I don't know how to solve it. I have a text file "cars.txt" and it has this information:
1950
Nissan Sentra
Ford Focus
1951
Mazda5
Mazda3
Toyota
1952
Chevy
I have to have 2 list boxes and one button. The first list box supposed to search through the file and populate years and when user select year and click on the button and it displays the corresponding cars models for this specific year. I have thoughts about using StreamReader but I don't know how to start.
Your help appreciated
Create a dictionary of string lists that will contain car lists with the year a key as well as a list for the years:
private readonly Dictionary<int, List<string>> _carsByYear =
new Dictionary<int, List<string>>();
private readonly List<int> _years = new List<int>();
Then you can fill it with
List<string> cars = null;
foreach (string line in File.ReadLines(#"C:\Users\Me\cars.txt")) {
if (!String.IsNullOrWhiteSpace(line)) {
if (Int32.TryParse(line, out int year)) { // We have a year
if (_carsByYear.TryGetValue(year, out var existingList)) {
cars = existingList;
} else {
// Add a new list with year as the key
_years.Add(year);
cars = new List<string>();
_carsByYear.Add(year, cars);
}
} else { // We have a car
cars.Add(line);
}
}
}
Now you can assign _years to the DataSource of the first ListBox. You can get the selected year (SelectedIndexChanged event) with
int year = (int)listBox1.SelectedItem;
With this year, you can get the cars list with
var selectedCarList = _carsByYear[year];
Assign it to the DataSource of the second ListBox.
now the is no error but nothing displayed. This is a very challenging
assignment. everyone in my class is stuck.
Works fine for me. Here's a variation with some examples of how you could use it:
private readonly SortedList<int, SortedSet<string>> _carsByYear = new SortedList<int, SortedSet<string>>();
private void button1_Click(object sender, EventArgs e)
{
SortedSet<string> cars = null;
string fileName = System.IO.Path.Combine(
System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"cars.txt");
foreach (string line in File.ReadLines(fileName))
{
if (!String.IsNullOrWhiteSpace(line))
{
if (Int32.TryParse(line, out int year))
{ // We have a year
if (!_carsByYear.ContainsKey(year))
{
cars = new SortedSet<string>();
_carsByYear.Add(year, cars);
}
else
{
cars = _carsByYear[year];
}
}
else
{ // We have a car
if (!cars.Contains(line))
{
cars.Add(line);
}
}
}
}
listBox1.DataSource = _carsByYear.Keys.ToList();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
listBox2.DataSource = _carsByYear[(int)listBox1.SelectedItem].ToList();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1 && listBox2.SelectedIndex != -1)
{
int year = (int)listBox1.SelectedItem;
string car = listBox2.SelectedItem.ToString();
label1.Text = year.ToString();
label2.Text = car;
}
else
{
label1.Text = "";
label2.Text = "";
}
}
If you still can't get it to work, give MORE DETAILS about the contents of the file and how you're supposed to use it in your interface.
Winforms, C#, VS2017
ImageList does not have an Insert method (however ListViewItemCollection does). I have tried a few different ways to insert a new image into the middle of a ListView and it's LargeImageList, but not getting it to work quite properly.
Anyone have any tried and true code that works properly?
This is what I have, but the images don't get synced properly to the items in the list.
protected void InsertThumbnail(string key, string keySelected)
{
var newImageList = new ImageList()
{
ImageSize = new Size(thumbWidth, thumbHeight)
};
var itemNew = new ListViewItem();
var foundSelected = false;
//lvAllPages.BeginUpdate();
for (int i = 0; i < lvAllPages.Items.Count; i++)
{
var item = lvAllPages.Items[i];
newImageList.Images.Add(item.Tag.ToString(), lvAllPages.LargeImageList.Images[i]);
if (item.Tag.ToString() == keySelected)
{
var image = batch.GetThumbnail(key);
newImageList.Images.Add(key, image);
itemNew = new ListViewItem()
{
BackColor = Color.Aquamarine,
ImageIndex = i,
Tag = key,
};
if (isLocal)
itemNew.Text = $"{GetFileName(key)} (insert) - {itemNew.ImageIndex}";
foundSelected = true;
}
if (foundSelected)
{
item.ImageIndex = item.ImageIndex + 1;
if (isLocal)
item.Text = $"{GetFileName(item.Tag.ToString())} - {item.ImageIndex}";
}
}
lvAllPages.LargeImageList.Dispose();
lvAllPages.LargeImageList = newImageList;
lvAllPages.Items.Insert(itemNew.ImageIndex, itemNew);
}
One more related thing, but not pertinent to the problems I am having. For anyone looking at this question and having similar issues, this helped with the issue of sorting items after inserting a new one. Default behavior when you insert a new ListViewItem at a given index, it will appear at the bottom of the list. I found this handy class to keep items sorted by index, which solved that problem:
class CompareByIndex : IComparer
{
private readonly ListView _listView;
public CompareByIndex(ListView listView)
{
this._listView = listView;
}
public int Compare(object x, object y)
{
int i = this._listView.Items.IndexOf((ListViewItem)x);
int j = this._listView.Items.IndexOf((ListViewItem)y);
return i - j;
}
}
And in the form load:
lvAllPages.ListViewItemSorter = new CompareByIndex(lvAllPages);
Obviously, that's a design decision. ImageList.Images is a ImageCollection and as such, it implements the IList interface.
Unfortunately, the Insert() method is allowed to throw a NotSupportedException. And that's what the list will do when used like a IList:
((IList)imageList.Images).Insert(5, new Bitmap(10,10));
System.NotSupportedException: 'Specified method is not supported.'
In order to have the images shown in a specific order, use the Add() method which takes the key:
imageList.Images.Add("1", new Bitmap(100,100));
That should also enable you to replace the image:
imageList.Images.RemoveByKey("1");
imageList.Images.Add("1", new Bitmap(200,200));
For that to work, you need to set the Sorting property:
listView1.Sorting = SortOrder.Ascending;
For storing additional information like path etc. use anotther data structure with the same key.
Here's the code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
ImageList imageList = new ImageList();
Dictionary<string, Metadata> metadata = new Dictionary<string, Metadata>();
private string dir = #"H:\temp";
private void button1_Click(object sender, EventArgs e)
{
// You would set this in the designer, probably
listView1.Sorting = SortOrder.Ascending;
listView1.View = View.LargeIcon;
listView1.LargeImageList = imageList;
// Make sure we start from the beginning
listView1.Items.Clear();
imageList.Images.Clear();
metadata.Clear();
// Add items
for (int i = 0; i < 10; i++)
{
var filename = "1 ("+(i+1)+").png"; // Just strange names I have
var fullFileName = Path.Combine(dir, filename);
imageList.Images.Add(i.ToString(), Bitmap.FromFile(fullFileName));
metadata.Add(i.ToString(), new Metadata{Path = fullFileName});
listView1.Items.Add(i.ToString(), "Image " + i, i.ToString());
}
// Update view
listView1.Refresh();
listView1.Invalidate();
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 3; i < 6; i++)
{
var filename = "1 ("+(i+2)+").png";
var fullFileName = Path.Combine(dir, filename);
// Change image
imageList.Images.RemoveByKey(i.ToString());
imageList.Images.Add(i.ToString(), Bitmap.FromFile(fullFileName));
// Match metadata and image
metadata[i.ToString()] = new Metadata{Path = fullFileName};
}
listView1.Refresh();
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
var key = listView1.SelectedItems[0].ImageKey;
label1.Text = metadata[key].Path;
}
else
{
label1.Text = "No image selected";
}
}
}
internal class Metadata
{
internal string Path;
}
I try to get index of selected item in ListBox:
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int index = listBox1.SelectedIndex;
}
When I select the second item it returns me index zero again.
Filling ListBox:
private void fillWorkListBox()
{
this.list = manager.works();
this.listBox1.DisplayMember = "name";
this.listBox1.ValueMember = "id";
for (var i = 0; i < this.list.works.Count; i++)
{
string name = "№" + this.list.works[i].id + " - " + this.list.works[i].name;
WorkModel work = new WorkModel();
work.name = name;
work.id = this.list.works[i].id;
listBox1.Items.Add(work);
}
}
It seems that your listbox has the SelectionMode property set to something different from the default. For example if the SelectionMode is MultipleSimple then you cannot use the SelectedIndex property because it is not a list of the elements selected. Instead you use the SelectedIndices collection
void listBox1_SelectedIndexChanged(object sender, EventArgs args)
{
foreach(int x in listBox1.SelectedIndices)
Console.WriteLine(x);
}
How can store name of dynamically created checkbox in a String array when I don't know how many checkbox will user select at runtime.
Say I have 10 dynamic checkboxes and out of 10 user select 6 checkboxes randomly now how can get the name of those selected checkboxes and store them in a String array.
I know how to use event handler on dynamic check box but confused how to declare Straing array when I don't know what will be be size of an array.
Here what I have done till now -
private void CheckBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox c = (CheckBox)sender;
//Label myLabel;
String str = null;
if (c.Checked == true)
{
str = c.Text;
gpBox[gpcount] = new GroupBox();
gpBox[gpcount].Name = "gpBox" + Convert.ToString(count);
gpBox[gpcount].Text = str;
gpBox[gpcount].Location = new Point(5, gpposition);
gpBox[gpcount].AutoSize = true;
this.Controls.Add(gpBox[gpcount]);
aCommand3 = new OleDbCommand("select * from batch_tbl where batch_branch LIKE '" + str + "'", main_connection);
aAdapter3 = new OleDbDataAdapter(aCommand3);
ds3 = new DataSet();
aAdapter3.Fill(ds3, "app_info");
ds3.Tables[0].Constraints.Add("pk_bno", ds3.Tables[0].Columns[0], true);
int batch_count = ds3.Tables[0].Rows.Count;
batchCheckBox = new CheckBox[batch_count];
//filling the groupbox with batch code by generating dynamic checkboxes
for (int j=0; j < batch_count; ++j)
{
batchCheckBox[j] = new CheckBox();
batchCheckBox[j].Name = "batch" + Convert.ToString(k);
batchCheckBox[j].Text = ds3.Tables[0].Rows[j][1].ToString();
Console.WriteLine(batchCheckBox[j].Text);
batchCheckBox[j].Location = new System.Drawing.Point(104 * position, 30);
gpBox[gpcount].Controls.Add(batchCheckBox[j]);
batchCheckBox[j].CheckStateChanged += new System.EventHandler(BatchBoxCheckedChanged);
position++;
count++;
Console.WriteLine(batchCheckBox[j].Name);
k++;
}
position = 1;
gpposition += 100;
}
else
{
count--;
this.Controls.RemoveByKey("lbl" + c.Name);
this.Update();
}
}
int total_batch = 1;
string[] batchname;
private void BatchBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox batchBox = (CheckBox)sender;
//Here I want to store name of checkbox in array
if (batchBox.Checked == true)
{
batchname = new String[total_batch];
total_batch++;
}
else
{
}
}
You can try this:
//Gets all checkbox's on the form
List<CheckBox> chks = Controls.OfType<CheckBox>().ToList();
//take only those who is checked, and select only their name property
List<string> names = chks.Where(c => c.Checked).Select(c => c.Name).ToList();
UPDATE
For testing you could print a list of the selected names:
string txt = "";
foreach(string name in names)
{
txt += name+" \n\r";
}
MessageBox.Show(txt);
Thank you everbody
}
list = new List<string>();
}
private void BatchBoxCheckedChanged(object sender, EventArgs e)
{
CheckBox batchBox = (CheckBox)sender;
//Here I want to store name of checkbox in array
if (batchBox.Checked == true)
{
list.Add(batchBox.Text);
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach(string prime in list) // Loop through List with foreach
{
Console.WriteLine(prime);
}
}
This is Done