listbox selectedindex only selecting last element - c#

I have a listbox that is bound to a list of objects from the database. I have a secondary list that has less objects that I want to use it to mark as selected elements.
cell = new HtmlTableCell();
List<ClasaAutor> listaAutori = DataTableToClasaAutor(dal.CitesteTotiAutori());
List<ClasaAutor> listaAutoriPublicatie = DataTableToClasaAutor(dal.CitesteTotiAutoriUneiPublicatii(guidPublicatie));
ListBox list = new ListBox();
list.SelectionMode = ListSelectionMode.Multiple;
list.ID = "cbAutori";
list.DataSource = listaAutori;
list.DataTextField = "NumeComplet";
list.DataValueField = "GuidAutor";
list.DataBind();
foreach (ClasaAutor autor in listaAutoriPublicatie)
{
for (int i = 0; i < list.Items.Count; i++)
{
if (list.Items[i].Value == autor.GuidAutor.ToString())
list.SelectedIndex = i;
}
}
cell.Controls.Add(list);
row.Cells.Add(cell);
The problem is that only my last element gets selected... why? How can I fix it?
My if is ok, it gets true 2 times...

Try this loop:
foreach (ClasaAutor autor in listaAutoriPublicatie)
{
foreach (ListItem item in list.Items)
{
if (item.Value == autor.GuidAutor.ToString())
item.Selected = true;
}
}

the problem in semantics, SelectedIndex of list can hold only one value, this is not collection
however you could make list item selected by setting the Selected value of it to true
list.Items[i].Selected = list.Items[i].Value == autor.GuidAutor.ToString();

Related

How to remove specific index from a list of datagridview rows

How to remove list of datagridview at specific index c#
List selectedRows = (from row in dataGridView2.Rows.Cast()
where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true
select row).ToList();
when this linq statement execute it will add whole row in selectedRows, i do not want to add coulmn 0 and 1 in List selectedRows so how i will achieve this ?
you have to provide list of column you want to select in select new as given below that will resolve issue
List selectedRows = (from row in dataGridView2.Rows.Cast()
where Convert.ToBoolean(row.Cells["checkBoxColumn"].Value) == true
select new {
Field1 = row.Field<string>("Field1"),
Field2 = row.Field<string>("Field2")
}).ToList();
Yes its a window form
i make checkbox using collection property of datagridview named as Select
i want to execute below code upon changing status of checkbox to check
foreach (DataGridViewRow item in dataGridView1.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
int n = dataGridView2.Rows.Add();
dataGridView2.Rows[n].Cells[0].Value = false;
dataGridView2.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
dataGridView2.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
dataGridView2.Rows[n].Cells[3].Value = item.Cells[3].Value.ToString();
dataGridView2.Rows[n].Cells[4].Value = item.Cells[4].Value.ToString();
dataGridView2.Rows[n].Cells[5].Value = item.Cells[5].Value.ToString();
dataGridView2.Rows[n].Cells[6].Value = item.Cells[6].Value.ToString();
dataGridView2.Rows[n].Cells[7].Value = item.Cells[7].Value.ToString();
dataGridView2.Rows[n].Cells[8].Value = item.Cells[8].Value.ToString();
dataGridView2.Rows[n].Cells[9].Value = item.Cells[9].Value.ToString();
dataGridView2.Rows[n].Cells[10].Value = item.Cells[10].Value;
for (int i = 0; i < dataGridView2.Columns.Count; i++)
if (dataGridView2.Columns[i] is DataGridViewImageColumn)
{
((DataGridViewImageColumn)dataGridView2.Columns[i]).ImageLayout = DataGridViewImageCellLayout.Stretch;
break;
}
foreach (DataGridViewRow row in this.dataGridView2.Rows)
{
row.Cells[0].Value = true;
}
}
}
above code is lies between button click event

Set Combobox selected item based on its ItemsValue

I have a Combobox, in which let's say that an item's Display Text is "School" and it's Item Value is 19. So i have stored this 19 into a DataGrid.
Then, i retrieve Combobox Value from DataGrid, then what i want to do is simply that based on value retrieved from DataGrid, combobox should set it's display Item or SelectedItem which have Value 19. In above scenario Combobox should display its selected item "School" if its value was 19.
So far i have wrote code upto this point. But it always giving me First Item of a Combobx.
DataGrid gd = (DataGrid)sender;
DataRowView rowSelected = gd.SelectedItem as DataRowView;
if(rowSelected!=null)
{
for (int i = 0; i < comboBox1.Items.Count;i++ )
{
if (Convert.ToString(comboBox1.SelectedValue) == Convert.ToString(rowSelected[14]))
{
index = comboBox1.Items.IndexOf(comboBox1.SelectedValue);
}
comboBox1.SelectedItem= comboBox1.Items[index];
}
textBox9.Text=rowSelected[14].ToString();
}
Now i am able to retrieve the Combobox Item, Based on its value which i am retrieving from the WPF DataGrid.
for (int i = 0;i <comboBox1.Items.Count; i++)
{
comboBox1.SelectedIndex = i;
if ((string)(comboBox1.SelectedValue) == Convert.ToString(rowSelected[14]))
{
index = i;
}
}
comboBox1.SelectedIndex = index;
Change your code to
if(rowSelected!=null)
{
int index = comboBox1.Items.IndexOf(rowSelected[14]);
comboBox1.SelectedItem = comboBox1.Items[index];
}
or
Use FindStringExact() method of combobox
int i = comboBox1.FindStringExact("Combo");
if(i >= 0)
{
}

Why when adding items to combobox it's adding the same item many times?

In the top of form1:
public class ComboboxItem
{
public string Text { get; set; }
public object Value { get; set; }
public override string ToString()
{
return Text;
}
}
List<string> results = new List<string>();
Then:
ComboboxItem item = new ComboboxItem();
var result = videoCatagories.Execute();
for (int i = 0; i < result.Items.Count; i++)
{
item.Text = result.Items[i].Snippet.Title;
item.Value = result.Items[i].Id;
comboBox1.Items.Add(item);
}
And in the end:
private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
{
MessageBox.Show((comboBox1.SelectedItem as ComboboxItem).Value.ToString());
}
What i wanted to do in general is to add to the combobox the titles and then when i select a title to get the title id.
For example i run the program and select the title Weather now i want to see in a messageBow.Show the id 1
There are 31 items.
When i use a breakpoint and look on result i see 31 items when i click on the first item in index 0 i see Id = "1" and then i click on snippet and see title "weather"
Then i do the same for item in index 1 and i see Id = "19" and in the snippet the title is "animals".
But for some reason it's adding each itertion the same item many times.
Create a new instance of ComboboxItem each time you want to add a new item to the combo box:
for (int i = 0; i < result.Items.Count; i++)
{
ComboboxItem item = new ComboboxItem();
item.Text = result.Items[i].Snippet.Title;
item.Value = result.Items[i].Id;
comboBox1.Items.Add(item);
}
Your code changes the properties of the same item instance for each entry in results, then adds it to the comboBox1.Items collection. Add inserts its argument to the Items collection, it doesn't copy its contents. As a result, when the combobox is rendered, all combobox items point to the same item. To avoid this, create a new item instance for each entry in results:
for (int i = 0; i < result.Items.Count; i++)
{
var item=new ComboboxItem
{
Text = result.Items[i].Snippet.Title,
Value = result.Items[i].Id
};
comboBox1.Items.Add(item);
}
or
var items=from item in result
select new ComboboxItem
{
Text = item.Snippet.Title,
Value = item.Id
};
comboBox1.Items.AddRange(items);
You could do a simple check to make sure that the combobox doesn't already contain it before doing the insert.
ComboboxItem item = new ComboboxItem();
var result = videoCatagories.Execute();
for (int i = 0; i < result.Items.Count - 1; i++)
{
if(!comboBox1.Items.Contains(item))
{
item.Text = result.Items[i].Snippet.Title;
item.Value = result.Items[i].Id;
comboBox1.Items.Add(item);
}
}
Or you can do like this article suggests and remove every item that is the same before adding the new item to remove conflicts, No Duplicate in a Listbox or using the same way to stop duplicates from a combobox too

WPF Listbox multiple selection clears after item removal

I have a ListBox in WPF with a DataBinded Xml Collection. I set the SelectionMode to Extended so the user can select multiple items. I have a RemoveItem command which iterates through the selecteditems and removes them from the list:
var selecteditems = this.SelectedItems;
for(int i = 0; i < selecteditems.Count; i++ )
{
ItemBox ouritem = (ItemBox)this.ItemContainerGenerator.ContainerFromItem(this.SelectedItems[i]);
XmlDataProvider prov = this.DataContext as XmlDataProvider;
XmlNode MainNode = prov.Document.SelectSingleNode("//MainNode");
MainNode.RemoveChild(selecteditems[i] as XmlNode);
}
The problem is that after the first item of a selection is deleted, the selection is cleared and the last item of the list is selected.
How can I keep the selection that I started with and make sure all the items are deleted?
How about the old 'take a copy first' approach?:
IList selectedItems = new List<YourDataType>();
foreach (YourDataType item in this.SelectedItems) selectedItems.Add(item);
for (int index = selectedItems.Count - 1; index >= 0; index--)
{
// remove each selected item here
}
Execute your loop in reverse iteration.
var selecteditems = this.SelectedItems;
for(int i = selecteditems.Count-1; i>=0; i-- )
{
ItemBox ouritem = (ItemBox)this.ItemContainerGenerator.ContainerFromItem(this.SelectedItems[i]);
XmlDataProvider prov = this.DataContext as XmlDataProvider;
XmlNode MainNode = prov.Document.SelectSingleNode("//MainNode");
MainNode.RemoveChild(selecteditems[i] as XmlNode);
}

How to cut, copy, paste any listview item in C#?

for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected)
{
listView1.Items[i].Remove();
}
}
This function simply deletes the selected item in listview.. but i want to cut it and paste it somewhere else.
It sounds like you want to remove the selected listitems and move them to another listview.
ListView sourceListView = new ListView();
ListView destListView = new ListView();
var selected = sourceListView.Items
.Cast<ListViewItem>()
.Where(x => x.Selected)
.ToList();
foreach (var item in selected)
{
sourceListView.Items.Remove(item);
destListView.Items.Add(item);
}

Categories

Resources