ListView selected item to TextBox - c#

First, I have filled a list object with the data from xml file. After that, I have filled a ListView with the necessary fields, without any problem. How can I get the index from the selected ListView item and then give appropriate value to some textbox?
This is the code for it:
private void Form1_Load(object sender, EventArgs e)
{
List<Tasks> taskList = new List<Tasks>();
listView1.Columns.Add("Date:");
listView1.Columns.Add("Job:");
listView1.Columns.Add("Client Name");
listView1.Columns.Add("Submitted by");
taskList = getTasks();
listView1.Items.Clear();
for (int i = 0; i < taskList.Count; i++)
{
Tasks task = taskList.ElementAt(i);
ListViewItem row = new ListViewItem();
row.Text=task.date.ToString();
row.SubItems.Add(task.job);
row.SubItems.Add(task.clientName);
row.SubItems.Add(task.submittedBy);
listView1.Items.Add(row);
}
}
public List<Tasks> getTasks()
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("data.xml");
XmlNodeList nodes = xmlDoc.DocumentElement.SelectNodes("/tasks/task");
List<Tasks> taskList = new List<Tasks>();
foreach (XmlNode node in nodes)
{
Tasks task = new Tasks();
task.id = Convert.ToInt32(node.SelectSingleNode("id").InnerText);
task.date = Convert.ToDateTime(node.SelectSingleNode("submittedDate").InnerText);
task.submittedBy = node.SelectSingleNode("submittedBy").InnerText;
task.clientName = node.SelectSingleNode("clientName").InnerText;
task.job = node.SelectSingleNode("job").InnerText;
task.taskCategory = node.SelectSingleNode("taskCategory").InnerText;
task.taskDescription = node.SelectSingleNode("taskDescription").InnerText;
task.hours = node.SelectSingleNode("hours").InnerText;
task.status = node.SelectSingleNode("status").InnerText;
task.isBilled = node.SelectSingleNode("isBilled").InnerText;
task.cost = node.SelectSingleNode("cost").InnerText;
task.followUpInfo = node.SelectSingleNode("followUpInfo").InnerText;
task.invoiceNumber = node.SelectSingleNode("quickBooksInvoiceNo").InnerText;
taskList.Add(task);
}
return taskList;
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
What I need is now how when I click an item from the listView1 to show some value in a textbox? But that value should be taken from the list object taskList, not from the xml document itself.

Store your task ID inside of your item's Tag property:
row.Tag = task.id;
Then handle ListView.SelectedIndexChanged event
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
var id = (int) listView1.SelectedItems[0].Tag;
var currenTask = taskList.Where(t => t.id == id).First();
textBox1.Text = currenTask.taskDescription; // for example
}
}
Also you should define your taskList in the class level, outside of your Form_Load method.Otherwise you can't access it from SelectedIndexChanged event.
List<Tasks> taskList = new List<Tasks>();
private void Form1_Load(object sender, EventArgs e)
{
...
}

Related

How to get the TreeNode a context menu item is attached to

In a Winforms application, I have this code:
private void BtnNuevoGrupo_Click(object sender, EventArgs e)
{
TreeNode newNode = TreDevices.Nodes[0].Nodes.Add("Nuevo grupo de validación");
TreDevices.Nodes[0].Expand();
TreDevices.SelectedNode = newNode;
newNode.Tag = "IN:0";
newNode.BeginEdit();
}
With that code, I am adding a tree node and starting edit immediately. Then, I have this code:
private async void TreDevices_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
e.Node.ContextMenuStrip = new ContextMenuStrip();
var itemEntrada = e.Node.ContextMenuStrip.Items.Add("Entrada");
itemEntrada.Click += InOutItem_Click;
}
Finally, I have this code to do some action when the context menu item is clicked:
private async void InOutItem_Click(object? sender, EventArgs e)
{
if (sender is not null)
{
var item = (ToolStripMenuItem)sender;
ContextMenuStrip menu = (ContextMenuStrip)item.Owner;
// HERE I NEED TO GET A REFERENCE TO THE TreeNode
}
}
In InOutItem_Click I need to get a reference to the TreeNode that owns the menu. How can I do it?
I can only get a reference to the tree control by using item.Owner.SourceControl.
Have you considered just using the Tag property of itemEntrada?
private void TreDevices_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
{
e.Node.ContextMenuStrip = new ContextMenuStrip();
var itemEntrada = new ToolStripMenuItem
{
Text = "Entrada",
Tag = e.Node,
};
e.Node.ContextMenuStrip.Items.Add(itemEntrada);
itemEntrada.Click += InOutItem_Click;
}
private void InOutItem_Click(object sender, EventArgs e)
{
if ((sender is ToolStripMenuItem tsmi) && (tsmi.Tag is TreeNode node))
{
var item = (ToolStripMenuItem)sender;
ContextMenuStrip menu = (ContextMenuStrip)item.Owner;
MessageBox.Show($"Clicked {node.Text}");
}
}

How to compare the items of two list-boxes and copy the unique items to new list-box

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

Why multiply items in a ListView?

I created in the Loaded event of the main page, a List with some objects of my class "Regioni" and "Musei"
Then I added these items in a ListView, and SelectedItem event recovery the selected object and take it in a new page
private void Page_Loaded(object sender, RoutedEventArgs e)
{
reg.Add(
new Regioni
{
NomeRegione = "Toscana",
NomeProvincia = "Firenze"
});
reg.Add(
new Regioni
{
NomeRegione = "Toscana",
NomeProvincia = "Prato"
});
var gruppi = reg.OrderBy(x => x.NomeRegione).GroupBy(x => x.NomeRegione);
Museum.Source = gruppi;
mus.Add(
new Musei
{
NomeMuseo = "Galleria degli Uffizi",
Paese = "Firenze",
NumeroTel = "055294883",
IndirizzoEmail = "mbac-sspsae-fi#beniculturali.it",
PrezzoBiglietto = "8 € Intero, 4€ Ridotto\r\nGratuito inferiore 18 anni",
Apertura = "Da martedì a domenica,\r\nore 8,15-18,50 Chiusura: Lunedi,Capodanno,Natale,1° Maggio.",
IndirizzoWeb = "http://uffizi.firenze.it/",
Immagine="Assets/Immagini/galleria-uffizi1.jpg",
});
}
private async void ListView_ItemClick_TuttiMusei(object sender, ItemClickEventArgs e)
{
var NuovoMuseo = (Musei)e.ClickedItem;
this.Frame.Navigate(typeof(DettaglioMuseo), NuovoMuseo);
}
Why when I insert the object into the new page "DettaglioMuseo", and go back on the main page, in the ListView I find the same items twice?
This happens because the Loaded-event fires again and adds the items again.
So you should check if your Regionis already exist before adding them:
private void Page_Loaded(object sender, RoutedEventArgs e)
{
AddIfNotExists("Toscana", "Firenze");
AddIfNotExists("Toscana", "Prato");
var gruppi = ...
...
}
private void AddIfNotExists(string regione, string provincia)
{
if (!reg.Any(r => r.NomeProvincia == regione && r.NomeProvincia == provincia))
{
reg.Add(new Regioni { NomeRegione = regione, NomeProvincia = provincia });
}
}

Remove selected item from ListView from ImageFileCollectionViewModel

I'm trying to remove the selected Item file from the list-view and also from the directory but I couldn't succeed. How can i remove this.?
string destination_dir = System.IO.Directory.GetCurrentDirectory() + #"./4x6";
public ImggLList()
{
InitializeComponent();
ListViewImage.Items.Clear();
DataContextChanged += OnDataContextChanged;
ImageFileCollectionViewModel ImagesViewModel = new ImageFileCollectionViewModel();
ImageFileControler.CompleteViewList(ImagesViewModel, destination_dir);
ListViewImage.DataContext = ImagesViewModel;
}
OnDataContextChanged
private ImageFileCollectionViewModel _currentDataContext = null;
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (_currentDataContext == DataContext) return;
if (_currentDataContext != null)
_currentDataContext.SelectedImageFileViewModels = null;
_currentDataContext = DataContext as ImageFileCollectionViewModel;
if (_currentDataContext != null)
_currentDataContext.SelectedImageFileViewModels = ListViewImage.SelectedItems;
}
Button Function:
private List<ImageFileViewModel> copyOfSelection;
private ImageFileCollectionViewModel imageFileCollection;
private void Delte_Photo_Click(object sender, RoutedEventArgs e)
{
copyOfSelection = imageFileCollection.SelectedImageFileViewModels.Cast<ImageFileViewModel>().ToList();
foreach (ImageFileViewModel ifvm in copyOfSelection)
{
copyOfSelection.Remove(ifvm);
File.Delete(destination_dir);
}
}
NullExeception Error:
for (int i = 0; i < copyOfSelection.Count; i++)
{
copyOfSelection.RemoveAt(i);
File.Delete(destination_dir);
}

objects in datagridview

Im adding objects to a datagridview ( only one kind) through a list
ej.
List<Material> mater = new List<Material>();
DataGridView dgvMAterial = new DataGridView();
dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
dgvMaterial.DataSource = mater;
But every time I click over the datagrid I get an indexoutofrangeexeption.
Can somone tell me why?
thanks
here is my whole code for the form
public partial class inicio : Form
{
private string ConnectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=data.mdf;Integrated Security=SSPI;";
//private string ConnectionString = "Server=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\data\\data_data.mdf.mdf; Database=data.mdf;Trusted_Connection=Yes;";
private ISessionFactory sessionFactory;
List<Material> mater = new List<Material>();
List<Salarios> salar = new List<Salarios>();
IBindingList mind = new BindingList<Salarios>();
Productos prod;
public inicio()
{
InitializeComponent();
sessionFactory = nhn.BusinessObjects.Initialize.CreateSessionFactory(ConnectionString);
dgvMaterial.DataSource = mater;
}
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmMaterial material = new costeos.Catalogos.frmMaterial(ConnectionString);
material.ShowDialog(this);
material.Dispose();
}
private void salariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmSalarios salarios = new costeos.Catalogos.frmSalarios(ConnectionString);
salarios.ShowDialog(this);
salarios.Dispose();
}
private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmAddRemuneraciones rem = new costeos.Catalogos.frmAddRemuneraciones(ConnectionString);
rem.ShowDialog(this);
rem.Dispose();
}
private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
{
Catalogos.frmAddAdmin adm = new costeos.Catalogos.frmAddAdmin(ConnectionString);
adm.ShowDialog(this);
adm.Dispose();
}
private void agregarToolStripMenuItem2_Click(object sender, EventArgs e)
{
Catalogos.frmAddInsumosInd insumos = new costeos.Catalogos.frmAddInsumosInd(ConnectionString);
insumos.ShowDialog(this);
insumos.Dispose();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void inicio_Load(object sender, EventArgs e)
{
LlenaCampos();
}
private void LlenaCampos()
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var mat = session.CreateCriteria(typeof(Material))
.List<Material>();
var sal = session.CreateCriteria(typeof(Salarios))
.List<Salarios>();
transaction.Commit();
cmbMaterial.DataSource = mat;
cmbMaterial.DisplayMember = "Nombre";
cmbSalarios.DataSource = sal;
cmbSalarios.DisplayMember = "Nombre";
cmbMIndirecta.DataSource = sal;
cmbMIndirecta.DisplayMember = "Nombre";
}
}
}
private void btnAddMaterial_Click(object sender, EventArgs e)
{
materialBindingSource.DataSource = null;
//dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
//dgvMaterial.DataSource = mater;
dgvMaterial.DataSource = materialBindingSource;
materialBindingSource.DataSource = mater;
materialBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
dgvSalarios.DataSource = null;
salar.Add((Salarios)cmbSalarios.SelectedValue);
dgvSalarios.DataSource = salar;
}
private void button3_Click(object sender, EventArgs e)
{
dgvMIndirecta.DataSource = null;
mind.Add((Salarios)cmbMIndirecta.SelectedValue);
dgvMIndirecta.DataSource = mind;
}
private void button1_Click(object sender, EventArgs e)
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
if (prod == null)
{
prod = new Productos { CargasTurno = float.Parse(txtCargasTurno.Text), CavidadesMolde = int.Parse(txtCavidadesMolde.Text), Clave = txtClave.Text, Comentarios = txtComentarios.Text, MezclasTurno = float.Parse(txtMezclasTurno.Text), Moldes = int.Parse(txtMoldes.Text), Nombre = txtNombre.Text, Peso = float.Parse(txtPesoTotal.Text), TotalPza = int.Parse(txtPzasTotales.Text), Turnos = int.Parse(txtTurnos.Text) };
session.Save(prod);
transaction.Commit();
}
foreach (DataGridViewRow dr in dgvMaterial.Rows)
{
Material m = dr.DataBoundItem as Material;
m.Materiales
PMaterial mat = new PMaterial { Material = dr.DataBoundItem as Material, Cantidad = float.Parse(dr.Cells["Cantidad"].Value.ToString()), Fecha = DateTime.Now, Producto = prod };
session.Save(mat);
}
transaction.Commit();
session.Close();
}
}
}
}
}
That's probably not DGV problem, but with this combo box. Show us the code that fills combo box and sets its properties.
If you are casting to Material class you should probably use SelectedItem instead of SelectedValue. (unless you exactly know what you're doing)
I would guess that you have an event-handler that isn't happy. What exactly does the message say?
You might also be having problems if you are adding the same Material instance to the list multiple times; since IndexOf will only find the first occurrence. This line makes me very suspicious:
mater.Add((Material)cmbMaterial.SelectedValue);
since it could potentially (on consecutive clicks / etc) do exactly this.
Note: if you used BindingList<T> instead all you'd have to doo is Add(...) - no resetting required:
field:
BindingList<Material> mater = new BindingList<Material>();
init grid:
dgvMaterial.DataSource = mater;
add item:
mater.Add(newInstance);
If you assign data source to the DGV you should check element count - if zero then assign null. I don't know why this is the way it is, but I'm doing it in all my forms.
//I'm still analysing the rest of the code

Categories

Resources