ListBox get selected index? - c#

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);
}

Related

How Equal ComboBox Items to Array Items

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.

move items within a listbox that filled from list of keyvaluepair

I have a list of integers.5 items max.These 5 integers shows 5 indexes of listbox items.I want to move this items in the first 5 places of this listbox.This listbox is filled from a list with this code
uList.Add(new KeyValuePair<int, string>(item.Id, item.Name));
listBoxHome.DataSource = uList;
listBoxHome.DisplayMember = "Value";
listBoxHome.ValueMember = "Key";
indexes is the list of integers refer to index of items.
game.listBoxHome.BeginUpdate();
for (int i = 0; i < 5; i++)
{
foreach (int PlayingInd in indexes)
{
HomeList.Insert(i, HomeList[PlayingInd]);
HomeList.RemoveAt(PlayingInd);
}
}
game.listBoxHome.DataSource = HomeList;
game.listBoxHome.DisplayMember = "Value";
game.listBoxHome.ValueMember = "Key";
game.listBoxHome.EndUpdate();
I use this code to one form:
public void button7_Click(object sender, EventArgs e)
{
Sub sub = new Sub();
foreach (ListItem item in listBox2.Items)
{
uList.Add(new KeyValuePair<int, string>(item.Id, item.Name));
}
sub.HomeList = uList;
}
And in the other form:
private BindingList<KeyValuePair<int, string>> Homelist;
public BindingList<KeyValuePair<int, string>> GetHomelist
{
get { return Homelist; }
set { Homelist = value; }
}
private void button2_Click(object sender, EventArgs e)
{
BindingList<int> indexes = new BindingList<int>();
foreach (int indexChecked in checkedListBox1.CheckedIndices)
{
indexes.Add(indexChecked);
}
Game game = new Game();
foreach (int PlayingInd in indexes)
{
Homelist.Insert(0, Homelist[PlayingInd]);
Homelist.RemoveAt(PlayingInd + 1);
}
game.GetHomelist = Homelist;
this.Close();
}
solved

bind many dropdownlist in a continous fashion

Hi all i need to bind a list of dropdown to values in database.Each drop down will be inside a panel and i have named it as ddlxx1,ddlxx2,ddlxx3 in a continuous fashion. all these drop down list will have the same data source.Is there any way to bind these control in a loop or should i find control each time which is in panel then bind it?
Something like:
for(int i=1;i<=10;i++)
{
ddlxx+"i".DataSource = Prod.GetValues();
ddlxx+"i".DataTextField = "ComponentID";
ddlxx+"i".DataValueField = "ComponentName";
ddlxx+"i".DataBind();
}
Please help
If your drop down lists are added to the mark-up you can simply do the following:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
for(int i=1;i<=10;i++)
{
var ddl = FindControl("ddlxx" + i) as DropDownList;
if (ddl != null)
{
BindDropDown(ddl);
}
}
}
}
private void BindDropDown(DropDownDataList ddl)
{
ddl.DataSource = Prod.GetValues();
ddl.DataTextField = "ComponentID";
ddl.DataValueField = "ComponentName";
ddl.DataBind();
}
Try this:
for (int i = 1; i <= 10; i++)
{
DropDownList drp = (DropDownList)panel1.FindControl("ddlxx" + i.ToString());//panel1 is your panel which contain dropdown ddlxx1,ddlxx2,ddlxx3...
drp.DataSource = Prod.GetComponents();
drp.DataTextField = "ComponentID";
drp.DataValueField = "ComponentName";
drp.DataBind();
}

How to store name of dynamic checkbox in an String array

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

Combobox SelectedItem not working propely

I'm trying to retrieve the selected item from a combobox, though i can't get it to work.
Form1 form = new Form1();
string cpuCount = form.comboBox1.SelectedItem.ToString();
Now, this is not returning anything. BUT, if i insert this code in my InitializeComponent(), it selects item with index = 3, and return that proper item.
comboBox1.SelectedIndex = 3;
Why does it behave like this? If I now select for example item with index = 5, it still will think the selected item is the one with index = 3.
---------- I think i should expand to show you how my code looks.
Form1 - adding all items to the comboboxes.
public partial class Form1 : Form
{
Profile profile = new Profile();
public Form1()
{
InitializeComponent();
Profile profile = new Profile();
string[] prof = profile.getProfiles();
foreach (var item in prof)
{
comboBox5.Items.Add(Path.GetFileNameWithoutExtension(item));
}
int ram = 1024;
for (int i = 0; i < 7; i++)
{
comboBox4.Items.Add(ram + " GB");
ram = ram * 2;
}
int vram = 512;
string size;
for (int i = 0; i < 5; i++)
{
if(vram > 1000)
{
size = " GB";
}
else
{
size = " MB";
}
comboBox2.Items.Add(vram + size);
vram = vram * 2;
}
for (int i = 1; i < 5; i++)
{
comboBox1.Items.Add(i * 2);
}
for (int i = 0; i < 5; i++)
{
comboBox3.Items.Add(i * 2);
}
private void button3_Click(object sender, EventArgs e)
{
string current = profile.currentProfile();
profile.saveProfile(current);
}
}
So, button3 is my "save"button.
And here is my "Profile"-class
class Profile
{
public string folder { get; set; }
public Profile()
{
this.folder = "Profiles";
if (!File.Exists(folder))
{
Directory.CreateDirectory(folder);
File.Create(folder + "/default.cfg").Close();
}
}
public string[] getProfiles()
{
string[] files = Directory.GetFiles(folder);
return files;
}
public void saveProfile(string filename)
{
Form1 form = new Form1();
string cpuCount = "cpuCount=" + form.comboBox1.SelectedItem;
string RAM = "maxRAM=" + form.comboBox4.SelectedItem;
string VRAM = "maxVRAM=" + form.comboBox2.SelectedItem;
string threads = "cpuThreads=" + form.comboBox3.SelectedItem;
string path = folder + "/" + filename;
StreamWriter sw = new StreamWriter(path);
string[] lines = { cpuCount, RAM, VRAM, threads };
foreach (var item in lines)
{
sw.WriteLine(item);
}
sw.Close();
}
public string currentProfile()
{
Form1 form = new Form1();
string selected = form.comboBox5.SelectedValue + ".cfg".ToString();
return selected;
}
}
Thank you.
The problem is that there is nothing selected in your ComboBox. You create your form and then, without previous user interaction, you want to get the SelectedItem which is null at that moment.
When you create ComboBox control and fill it with items, SelectedItem property is null until you either programratically set it (by using for example comboBox1.SelectedIndex = 3) or by user interaction with the control. In this case you are not doing anything of the above and that is why you are geting the mentioned error.
EDIT Based on the edited question
Change your code like this:
first change the saveProfile method so you could pass the four strings which you write into the text file. Note that you could alternatively pass the reference of the form but I wouldn't suggest you that. So change the method like this:
public void saveProfile(string filename, string cpuCount, string RAM , string VRAM , string threads)
{
string path = folder + "/" + filename;
using(StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("cpuCount=" + cpuCount);
sw.WriteLine("maxRAM=" + RAM );
sw.WriteLine("maxVRAM=" + VRAM );
sw.WriteLine("cpuThreads=" + threads);
}
}
And then call it from button3 Click event handler like this:
private void button3_Click(object sender, EventArgs e)
{
string current = profile.currentProfile();
string cpuCount = this.comboBox1.SelectedItem.ToString();
string RAM = this.comboBox4.SelectedItem.ToString();
string VRAM = this.comboBox2.SelectedItem.ToString();
string threads = this.comboBox3.SelectedItem().ToString();
profile.saveProfile(current, cpuCount, RAM, VRAM, threads);
}
Or alternatively
private void button3_Click(object sender, EventArgs e)
{
string current = profile.currentProfile();
profile.saveProfile(current, this.comboBox1.SelectedItem.ToString(), this.comboBox4.SelectedItem.ToString(), this.comboBox2.SelectedItem.ToString(), this.comboBox3.SelectedItem().ToString());
}
From what I can see, you are calling form.comboBox1.SelectedItem.ToString() right after the creation of Form1. This means that the cpuCount variable is initialized right after the form is created, thus far before you have the chance to change the selected item with your mouse.
If you want to retrieve the value of the combobox after it is changed, you can use the SelectedIndexChanged event.
First of all, add a Form_Load Event and put your code in the handler. (use constructor for property initialization and other variable initialization)
private void Form1_Load(object sender, EventArgs e)
{
this.comboBox1.SelectedItem= 5; // This will set the combo box to index 5
string cpuCount = this.comboBox1.SelectedText; // This will get the text of the selected item
}
so you get the value of item at index 5 in cpuCount variable.
The selected clause gives you the values AFTER you have selected something, by default(when you run your app) there is nothing selected in the comoboBox, hence, it displays the value as null, after selecting the item you can use the combobox's selectedItem, selectedIndex, selectedText and selectedValue properties.
You can also use databinding to display items in the combobox, which in my view is a better way then adding the items manually.
to databind your combobox you can use,
// Bind your combobox to a datasource, datasource can be a from a database table, List, Dataset, etc..
IDictionary<int, string> comboDictionary = new Dictionary<int, string>();
comboDictionary.Add(1, "first");
comboDictionary.Add(2, "second");
comboDictionary.Add(3, "third");
comboBox1.DataSource = comboDictionary;
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
//
And here now you can use combobox1.SelectedIndex to go through the item collection in the datasource :) and it will give you the value against your keys when you use combobox1.SelectedValue. Hope this helps.
Your ComoboBox doesn't have items in it. So it will not return properly. You are accessing combobox selected value rights after making form object.
And if it comboBox has items then nothing is being selected. By default nothing is selected in comboBox. You need to set it. Use this. What it returns? Set comboBox.SelectedIndex and then get selectedItem.
int selectedIndex = form.comboBox1.SelectedIndex;
Try this. Add some items in ComboBox and then get selectedItem.
Form1 form = new Form1();
form.comboBox1.Add("Item 1");
form.comboBox1.Add("Item 2");
form.comboBox1.Add("Item 3");
form.comboBox1.SelectedIndex = 1;
string cpuCount = form.comboBox1.SelectedItem.ToString();

Categories