Why multiply items in a ListView? - c#

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

Related

How to update the text in a listView with the DownloadFileAsync progress percentage?

I am currently making a podcast client to download episodes. I have got a listView filled with the episodes for a feed and then when you double click on one it places it into a separate 'downloads' lisview which has a 'name' and a 'progress' column.
The problem I am having is trying to individually update each progress while downloading asynchronously. As I am not sure of how to keep track of the progress for each ListViewItem and how to reference it in the downloadProgressChanged function.
private void lvPodDownloads_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lvPodEpisodes.SelectedItems.Count == 1) // Check if an item is selected just to be safe
{
ListViewItem item = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])item.Tag;
txtTitle.Text = epInfo[0];
txtDesc.Text = epInfo[1];
try
{
imgFeedImage.Source = new BitmapImage(new Uri((Environment.CurrentDirectory + "\\..\\..\\feedImages\\" + epInfo[3])));
}
catch (Exception) // If it fails to set the image (Eg. It's non-existent) It will leave it blank
{
imgFeedImage.Source = null;
}
}
}
private void lvPodEpisodes_MouseDoubleClick(object sender, MouseButtonEventArgs e) // Downloading the episode in here
{
if (e.ChangedButton == MouseButton.Left) // Left button was double clicked
{
ListViewItem selected = (ListViewItem)lvPodEpisodes.SelectedItem;
string[] epInfo = (string[])selected.Tag;
Uri downloadUrl = new Uri(epInfo[2]);
List<Episode> downloading = new List<Episode>();
downloading.Add(new Episode() { Title = epInfo[0], Progress = "0%" });
lvPodDownloads.Items.Add((new Episode() { Title = epInfo[0], Progress = "0%" }));
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
}
}
}
static int intDownloadProgress = new int();
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
intDownloadProgress = e.ProgressPercentage;
}
private void Completed(object sender, AsyncCompletedEventArgs e)
{
MessageBox.Show("Download completed!");
}
This is a code sample of the downloading section of the program.
Here is an image of what I have so far:
https://s33.postimg.cc/gthzioxlr/image.png
You should add an extra argument to your ProgressChanged method.
private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e, Episode curEpisode)
{
curEpisode.Progress = $"{e.ProgressPercentage} %";
}
And to modify the handler setting like that:
List<Episode> downloading = new List<Episode>();
var newEpisode = new Episode() { Title = epInfo[0], Progress = "0%" };
downloading.Add(newEpisode);
lvPodDownloads.Items.Add(newEpisode);
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler((sender, e) => ProgressChanged(sender, e, newEpisode));
}
The static property intDownloadProgress is then useless.
You should also think about using an observable collection for the episode list and using it for the binding via the XAML code.

How to fix the drag and drop using dev express in c# after fetching data and setting tag property

enter image description here
namespace Implementer
{
public partial class MainForm : Form
{
#region intit and globals
public MainForm()
{
InitializeComponent();
DevExpress.XtraGrid.Views.Grid.GridView gridView = new DevExpress.XtraGrid.Views.Grid.GridView();
var transactions = new ObservableCollection<Item>();
for (int i = 0; i <= 100; i++)
{
transactions.Add(new Item { Content = "Item " + i });
}
grdTransactions.AllowDrop = true;
grdTransactions.DataSource = transactions;
dgmWf.AddingNewItem += (s, e) => transactions.Remove(e.Item.Tag as Item);
}
Point mouseDownLocation;
GridHitInfo gridHitInfo;
#endregion
#region events
public void Mainform_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'vA_ERP4_ADMINDataSet.SYSTEM_MODULES' table. You can move, or remove it, as needed.
//Project initiation
//Fill drop down for project list
cmbProject.SelectedIndex = 0;
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtResult = dataAccess.ExecuteQueryDataSet("select MODULE_CODE, MODULE_DESC from SYSTEM_MODULES where module_is_active=1").Tables[0];
cmbProject.DisplayMember = "MODULE_DESC";
cmbProject.ValueMember = "MODULE_CODE";
cmbProject.DataSource = dtResult;
}
private void cmbProject_SelectedIndexChanged(object sender, EventArgs e)
{
lblCurrentProject.Text = cmbProject.Text;
if (cmbProject.Text != null)
{
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable dtTransactions = dataAccess.ExecuteQueryDataSet("select sys_trans_id, sys_trans_desc1 from WF_SYSTEM_TRANS where MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
grdTransactions.DataSource = dtTransactions;
}
}
private void btnSalesInvoice_Click(object sender, EventArgs e)
{
int sysTransId = 1001;
FillTransactionDetails(sysTransId);
}
#endregion
#region drag drop
private void grdTransactions_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left && CanStartDragDrop(e.Location))
{
StartDragDrop();
}
}
private void grdTransactions_MouseDown(object sender, MouseEventArgs e)
{
gridHitInfo = grdVTransactions.CalcHitInfo(e.Location);
mouseDownLocation = e.Location;
}
private void grdTransactions_MouseLeave(object sender, EventArgs e)
{
if (gridHitInfo != null)
gridHitInfo.View.ResetCursor();
gridHitInfo = null;
}
private bool CanStartDragDrop(Point location)
{
return gridHitInfo.InDataRow && (Math.Abs(location.X - mouseDownLocation.X) > 2 || Math.Abs(location.Y - mouseDownLocation.Y) > 2);
}
public void StartDragDrop()
{
var draggedRow = gridHitInfo.View.GetRow(gridHitInfo.RowHandle) as Item;
var tool = new FactoryItemTool(" ", () => " ", diagram => new DiagramShape(BasicShapes.Rectangle) { Content = draggedRow.Content, Tag = draggedRow }, new System.Windows.Size(150, 100), false);
dgmWf.Commands.Execute(DiagramCommandsBase.StartDragToolCommand, tool, null);
}
#endregion
#region function
private void FillTransactionDetails(int systemTransactionId)
{
//Fill document
//Fill steps
DataAccess dataAccess = new DataAccess(GlobalFunctions.GetConnectionString());
DataTable transactionDetails = dataAccess.ExecuteQueryDataSet("SELECT DOC_TYPE_DESC1 FROM WF_SYSTEM_TRANS_DT WHERE SYS_TRANS_ID=1001 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionDetails.Rows.Add();
grdDocuments.DataSource = transactionDetails;
grdDocuments.Columns["Details"].DisplayIndex = 2;
grdDocuments.Columns["Delete"].DisplayIndex = 2;
DataTable transactionSteps = dataAccess.ExecuteQueryDataSet("select WF_STEP_DESC1 from WF_STEPS where wf_id= 10101 and MODULE_CODE= '" + cmbProject.Text + "'").Tables[0];
transactionSteps.Rows.Add();
grdSteps.DataSource = transactionSteps;
}
#endregion
}
public class Item
{
public string Content { get; set; }
}
}
I don't really know where is the mistake and have been looking at it for the past few days and searching for an answer but no luck so I'd be so happy if you could help me out. It was working without the data fetching. but after calling the data it doesn't work. drag it from the grid view and when it reaches the diagram control it would turn into a rectangle with a tag property of it's ID.. With regards to the connection string.. I created a global function to just call it on the main form.

Modern UI Dialog result issues

I am working with Modern UI and attempting to make a dialog box that asks a question and then waits for a response. I can do this with messagebox but though I would try using modern UI. I am unsure of how to get the button clicked value.
if (testapp.linkvalue != "NULL")
{
var v = new ModernDialog
{
Title = "my test",
Content = "pewpew lazers rule. If you agree click ok"
};
v.Buttons = new Button[] { v.OkButton, v.CancelButton };
var r = v.ShowDialog();
if (????????????????)
{
MessageBox.Show("ok was clicked");
}
else
{
MessageBox.Show("cancel was clicked");
}
}
if (testapp.linkvalue != "NULL")
{
var v = new ModernDialog
{
Title = "my test",
Content = "pewpew lazers rule. If you agree click ok"
};
v.OkButton.Click += new RoutedEventHandler(OkButton_Click);
v.Buttons = new Button[] { v.OkButton, v.CancelButton };
var r = v.ShowDialog();
}
//And Then Create OkButtonClick
private void OkButton_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("ok was clicked");
}
private void CommonDialog_Click(object sender, RoutedEventArgs e)
{
var dlg = new ModernDialog {
Title = "Common dialog",
Content = new LoremIpsum()
};
dlg.Buttons = new Button[] { dlg.OkButton, dlg.CancelButton};
dlg.ShowDialog();
this.dialogResult.Text = dlg.DialogResult.HasValue ? dlg.DialogResult.ToString() : "<null>";
this.dialogMessageBoxResult.Text = dlg.MessageBoxResult.ToString();
}
It might be another solution using extension method.
var r = v.ShowDialogOKCancel();
if (r==MessageBoxResult.OK)
{
MessageBox.Show("ok was clicked");
}
else
{
MessageBox.Show("cancel was clicked");
}
static class ModernDialogExtension
{
static MessageBoxResult result;
public static MessageBoxResult ShowDialogOKCancel(this FirstFloor.ModernUI.Windows.Controls.ModernDialog modernDialog)
{
result = MessageBoxResult.Cancel;
modernDialog.OkButton.Click += new RoutedEventHandler(OkButton_Click);
modernDialog.Buttons = new Button[] { modernDialog.OkButton, modernDialog.CloseButton };
modernDialog.ShowDialog();
return result;
}
private static void OkButton_Click(object sender, RoutedEventArgs e)
{
result = MessageBoxResult.OK;
}
}

ListView selected item to TextBox

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)
{
...
}

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