I have two ListBoxes. I want to copy SelectedItem from the first ListBox into Second one.
Why this code does not work ?
private void frm_addDispatchBoard2_Load(object sender, EventArgs e)
{
using(propertiesManagementDataContext db = new propertiesManagementDataContext())
{
var Buildings = db.Buildings.Select(q => new { q.BuildingLandNumber, q.BuildingId });
listBox_allBuildings.DataSource = Buildings;
listBox_allBuildings.DisplayMember = "BuildingLandNumber";
listBox_allBuildings.ValueMember = "BuildingId";
}
}
private void btn_addBuilding_Click(object sender, EventArgs e)
{
if(listBox_allBuildings.SelectedIndex > 0)
{
listBox_selectedBuildings.Items.Add(listBox_allBuildings.SelectedItem);
}
}
The result I got:
try this I am not sure why you are looking for a Contains but if you really need that look at the difference between SelectedValue and SelectedItem
Use this code right here as a test to see if the expected value shows up in a MessageBox
string selected = listBox_allBuildings.GetItemText(listBox_allBuildings.SelectedValue);
MessageBox.Show(selected);
this should help you to see the values in the Listbox on the right
private void btn_addBuilding_Click(object sender, EventArgs e)
{
if(listBox_allBuildings.SelectedIndex != -1)
{
var selected = listBox_allBuildings.GetItemText(listBox_allBuildings.SelectedValue);
listBox_selectedBuildings.Items.Add(selected);
}
}
Related
I have 3 list boxes and when I have three things selected and click the delete button it deleted the text in the first list box but then gives a exception saying a value of -1 is not valid for index. This is my current code:
lstBoxOne.Items.RemoveAt(lstBoxOne.SelectedIndex);
lstBoxTwo.Items.RemoveAt(lstBoxTwo.SelectedIndex);
lstBoxThree.Items.RemoveAt(lstBoxThree.SelectedIndex);
wondered if theirs a way to delete all three selected text with a click of a button
Edit: I have now put image of full expection
Full exception
Edit 2: Here is an example with full code
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void LstBoxOne_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxOne.SelectedIndex;
lstBoxTwo.SelectedIndex = deleteD;
lstBoxThree.SelectedIndex = deleteD;
}
private void BtnInsert_Click(object sender, EventArgs e)
{
lstBoxOne.Items.Add(this.txtOne.Text);
lstBoxTwo.Items.Add(this.txtTwo.Text);
lstBoxThree.Items.Add(this.txtThree.Text);
this.txtOne.Focus();
this.txtOne.Clear();
this.txtTwo.Focus();
this.txtTwo.Clear();
this.txtThree.Focus();
this.txtThree.Clear();
}
private void BtnDelete_Click(object sender, EventArgs e)
{
lstBoxOne.Items.RemoveAt(lstBoxOne.SelectedIndex);
lstBoxTwo.Items.RemoveAt(lstBoxTwo.SelectedIndex);
lstBoxThree.Items.RemoveAt(lstBoxThree.SelectedIndex);
}
private void LstBoxTwo_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxTwo.SelectedIndex;
lstBoxOne.SelectedIndex = deleteD;
lstBoxThree.SelectedIndex = deleteD;
}
private void LstBoxThree_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxThree.SelectedIndex;
lstBoxOne.SelectedIndex = deleteD;
lstBoxTwo.SelectedIndex = deleteD;
}
}
}
}
The problem is due to the SelectedIndexChanged event on lstBoxOne.
Inside of BtnDelete_Click, when you remove the selected item from lstBoxOne this causes lstBoxOne.SelectedIndex to change. This causes LstBoxOne_SelectedIndexChanged to fire BEFORE the item is removed from lstBoxTwo and lstBoxThree. When LstBoxOne_SelectedIndexChanged finishes and returns to BtnDelete_Click, lstBoxTwo.SelectedIndex and lstBoxThree.SelectedIndex are both -1 and the Exception is occurring due to passing -1 to RemoveAt.
private void LstBoxOne_SelectedIndexChanged(object sender, EventArgs e)
{
var deleteD = lstBoxOne.SelectedIndex;
lstBoxTwo.SelectedIndex = deleteD;
lstBoxThree.SelecteIndex = deleteD;
}
private void DeleteBtn_Click(object sender, EventArgs e)
{
lstBoxOne.Items.RemoveAt(lstBoxOne.SelectedIndex); //This line triggers the SelectedIndexChanged event on lstBoxOne.
// By the time we get back to this function, lstBoxTwo and lstBoxThree have had
// their SelectedIndex set to -1. That is what is causing the exception to occur.
lstBoxTwo.Items.RemoveAt(lstBoxTwo.SelectedIndex); //Ooops! lstBoxTwo.SelectedIndex was set to -1 in LstBoxOne_SelectedIndexChanged.
}
A simple way to correct this would be to store the selected index of each ListBox before trying to remove any items. Also, protect yourself by checking for -1.
private void DeleteBtn_Click(object sender, EventArgs e)
{
int lstBoxOneIdx = lstBoxOne.SelectedIndex;
int lstBoxTwoIdx = lstBoxTwo.SelectedIndex;
int lstBoxthreeIdx = lstBoxThree.SelectedIndex;
if (lstBoxOneIdx > -1)
{
lstBoxOne.Items.RemoveAt(lstBoxOneIdx);
}
if (lstBoxTwoIdx > -1)
{
lstBoxTwo.Items.RemoveAt(lstBoxTwoIdx);
}
if (lstBoxThreeIdx > -1)
{
lstBoxThree.Items.RemoveAt(lstBoxThreeIdx);
}
}
I have three list boxes. The left and the middle list-box have some items. I want to compare the items in the left and middle list-box. I want to move the unique items to right side list-box from middle list-box and I want an expression handle.
I tried do it with the code underneath.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<string> FileNames = null;
private void Btn_FileFolder_Click(object sender, EventArgs e)
{
using (FolderBrowserDialog FBDfolder = new FolderBrowserDialog())
{
if (FBDfolder.ShowDialog() == DialogResult.OK)
{
lbl_FolderPath.Text = FBDfolder.SelectedPath;
FileNames = Directory.GetFiles(FBDfolder.SelectedPath).ToList();
lstbx_filefolder.DataSource = FileNames.Select(f => Path.GetFileName(f)).ToList();
lbl_NoOfFolderItems.Text = lstbx_filefolder.Items.Count.ToString();
}
}
}
private void Btn_TextFile_Click(object sender, EventArgs e)
{
OpenFileDialog textfile = new OpenFileDialog {
Filter = "text (*.txt)|*.txt"
};
if (textfile.ShowDialog() == DialogResult.OK)
{
lbl_filepath.Text = textfile.FileName;
string[] lines = File.ReadAllLines(lbl_filepath.Text);
lstbx_textfile.Items.AddRange(lines);
lbl_NoOfItems.Text = lstbx_textfile.Items.Count.ToString();
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_RemoveDuplicates_Click(object sender, EventArgs e)
{
var listboxfile = lstbx_filefolder.Items;
var listboxtext = lstbx_textfile.Items;
foreach (var itm in listboxfile)
{
if (listboxtext.Contains(itm)) listboxtext.Remove(itm);
}
}
private void btn_clear_Click(object sender, EventArgs e)
{
lstbx_filefolder.DataSource = null;
//lstbx_filefolder.Items.Clear();
lstbx_textfile.DataSource = null;
lstbx_textfile.Items.Clear();
}
}
}
When working with collections you could in many cases use Linq for these taks.
The first step in solving your problem would be to combine the lists into a single list
The next step would be to use Linq to get the unique string values from the list, this while assigning the result of the Linq query to a new List.
By using Distinct() the duplicate items are removed. Resulting in something like this:
private void btn_RemoveDuplicates_Click(object sender, EventArgs e)
{
var itemCollection = new List<string>();
itemCollection.AddRange(lstbx_filefolder.Items);
itemCollection.AddRange(lstbx_textfile.Items);
var uniqueCollection = itemCollection.Distinct().ToList();
// todo assign the values in the uniqueCollection to the source of the right listbox.
`rightListBox`.Datasource = uniqueCollection;
}
I'm trying to get the value of radio button selection to my listbox, but the listbox always gets the same value even though selection was different. Please help, I am a newbie to coding, I couldn't find any answers on the net either..
Here are the codes I've written:
void rdbtnOne_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnOne.Checked == true)
{
rdbtnOne.Text = "Men";
}
else
{
rdbtnOne.Text = "Women";
}
}
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Add(i + rdbtnOne.Text);
i++;
}
Ok, I have found the solution, FINALLY. The reason that my code did not work in the first place was because I tried to give value by equaling rdbtnOne.Text directly. Instead I created another value to equal it. All right here is how it worked for me:
string MenOrWomen;
void rdbtnTwo_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnTwo.Checked.Equals(true))
{
MenOrWomen = "Women";
}
else
{
MenOrWomen = "Men";
}
}
void rdbtnOne_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnOne.Checked.Equals(true))
{
MenOrWomen = "Men";
}
else
{
MenOrWomen = "Women";
}
}
int i = 1;
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Add(i + MenOrWomen);
i++;
}
I am trying to clear the contents of a listbox when a new tab is seleced. Here is what I got, but nothing happens.
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages["entryTab"])
{
readBox.Items.Clear();
reminderBox.Items.Clear();
}
}
Try something like this in your form load
tabControl1.Selecting += new TabControlCancelEventHandler(tabControl1_SelectedIndexChanged);
// Try this set null to DataSource
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.SelectedTab == tabControl1.TabPages["entryTab"])
{
readBox.DataSource = null;
reminderBox.DataSource = null;
}
}
I have found the closest reference of my problem on these links:
ComboBox has its old value after Clear()
Why selected index fires only once the Index of the ListItem is changed?
I have 4 comboboxes: cmbcountry, cmbstate, cmbdistrict and cmbcity. cmbcountry populates on load event by GetCountry() method. cmbstate populates by GetState(countryid) method, which takes cmbcountry's selectedvalue as argument and returns a list of relevant states and so on for cmbdistrict and cmbcity...
Problem is on selecting different item in cmbState, cmbDistrct is not populating with the proper items.
.E.g. states :"madhya pradesh", "Utter pradesh" , "Rajsthan"
For "Rajsthan", cmbdistrict is populating with relavent value, but for "Utter pradesh", cmbdistrict still has old value.
Here is the relevant code:
private void TestForm1_Load(object sender, EventArgs e)
{
cmbCountry.ItemSource = Lookups.Lookup.GetCountries();
}
private void cmbCountry_SelectionChangeCommitted(object sender, EventArgs e)
{
cmbState.Text = "";
cmbState.Clear();
cmbState.SelectedIndex = -1;
cmbState.SelectedItem = null;
//cmbState.Items.Clear();
int countryId = Convert.ToInt32(cmbCountry.SelectedValue);
cmbState.ItemSource = Lookups.Lookup.GetStates(countryId);
}
private void cmbState_SelectionChangeCommitted(object sender, EventArgs e)
{
cmbDistrict.Text = "";
cmbDistrict.Clear();
cmbDistrict.SelectedIndex = -1;
cmbDistrict.SelectedItem = null;
//cmbDistrict.Items.Clear();
int stateId = Convert.ToInt32(cmbState.SelectedValue);
cmbDistrict.ItemSource = Lookups.Lookup.GetDistricts(stateId);
}
private void cmbDistrict_SelectionChangeCommitted(object sender, EventArgs e)
{
cmbCity.Text = "";
cmbCity.Clear();
cmbCity.SelectedIndex = -1;
cmbCity.SelectedItem = null;
//cmbCity.Items.Clear();
int DistrictId = Convert.ToInt32(cmbDistrict.SelectedValue);
cmbCity.ItemSource = Lookups.Lookup.GetCities(DistrictId);
}
private void cmbBank_SelectionChangeCommitted(object sender, EventArgs e)
{
int bankId = Convert.ToInt32(cmbBank.SelectedValue);
cmbControlBranch.ItemSource = Lookups.Lookup.GetBranches(bankId);
}
I have all above methods to clear previous data in comboboxes ...and items.clear() is giving an error if i am using it.
Please tell me if there is any other relevant reference which I am missing .