Home Page
Articoli
Tips & Tricks
News
Forum
Archivio Forum
Blogs
Sondaggi
Rss
Video
Utenti
Chi Siamo
Contattaci
Username:
Password:
Login
Registrati ora!
Recupera Password
Home Page
Stanze Forum
App. WinForms / WPF .NET
DataTable e Datagrid in Wpf C#
mercoledì 08 aprile 2015 - 17.49
Elenco Threads
Stanze Forum
Aggiungi ai Preferiti
Cerca nel forum
Elenco Tags
C#
Vuelle
Profilo
| Newbie
1
messaggi | Data Invio:
mer 8 apr 2015 - 17:49
Salve a tutti,
ho creato un semplice programma WPF in cui gestisco dei dati contenuti in una tabella (DataTable) e che visualizzo nella finestra su di un controllo Datagrid.
Se tento di cancellare un record della DataTable dal gestore dell'evento clcick di un Button tutto funziona correttamente, e la stessa cosa succede se lo elimino all'interno di un gestore dell'evento Tick di un DispatcherTimer.
Il problema nasce quando tento di fare la stessa operazione utilizzando un BackgroundWorker: se cancello un record della tabella all'interno del gestore dell'evento DoWork, sulla Datagrid non vengono eliminati i records! Anzi, in realtà i dati dalla Datatable vengono cancellati ma è la finestra a non aggiornare la visualizzazione.
Provo a riportare un esempio di quello che ho fatto sperando che qualcuno possa aiutarmi:
<Window x:Class="WpfApplication2.MainWindow"
xmlns="
http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="
http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="489" Width="528">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80*"/>
<RowDefinition Height="379*"/>
</Grid.RowDefinitions>
<DataGrid x:Name="dgvTest" Grid.Row="1" ItemsSource="{Binding}"/>
<TextBox x:Name="rn" HorizontalAlignment="Left" Height="20" TextWrapping="Wrap" Text="1" VerticalAlignment="Top" Width="44" Margin="10,44,0,0" FontWeight="Bold"/>
<Button Name="Canc1" Content="Delete" HorizontalAlignment="Left" Height="31" Margin="59,39,0,0" VerticalAlignment="Top" Width="103" Click="Canc_Click"/>
<Button Name="Canc2" Content="Delete by worker" HorizontalAlignment="Left" Height="31" Margin="167,39,0,0" VerticalAlignment="Top" Width="165" Click="Canc2_Click"/>
<Button Name="Canc3" Content="Delete by Timer" HorizontalAlignment="Left" Height="31" Margin="340,39,0,0" VerticalAlignment="Top" Width="170" Click="Canc3_Click"/>
<Button Name="Carica" Content="Crea Lista" HorizontalAlignment="Left" VerticalAlignment="Top" Width="500" Margin="10,10,0,0" Click="Carica_Click"/>
</Grid>
</Window>
class Dati
{
public DataTable tbList;
public Dati(string NomeLista)
{
tbList = new DataTable(NomeLista);
tbList.Columns.Add(new DataColumn("V1", System.Type.GetType("System.Int32")));
tbList.Columns.Add(new DataColumn("V2", System.Type.GetType("System.String")));
}
public bool DelRec(int id)
{
try
{
DataRow[] Rows = tbList.Select("V1=" + id.ToString());
if (Rows.Length == 1)
{
Rows[0].Delete();
tbList.AcceptChanges();
return true;
}
}
catch (Exception )
{}
return false;
}
}
public partial class MainWindow : Window
{
Dati dati1;
BackgroundWorker worker;
DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
dati1 = new Dati("Lista1");
dgvTest.DataContext = dati1.tbList.DefaultView;
worker = new BackgroundWorker();
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
worker.WorkerReportsProgress = true;
}
private void Carica_Click(object sender, RoutedEventArgs e)
{
// carico dei dati di esempio
for (int a = 1; a < 10; a++)
{
DataRow r = dati1.tbList.NewRow();
r["V1"] = a;
r["V2"] = "V" + a.ToString();
dati1.tbList.Rows.Add(r);
}
}
private void Canc_Click(object sender, RoutedEventArgs e)
{
// cancello il record -> la Datagrid si aggiorna correttamente
dati1.DelRec(int.Parse(rn.Text));
}
private void Canc2_Click(object sender, RoutedEventArgs e)
{
Canc1.IsEnabled = false; Canc2.IsEnabled = false; Canc3.IsEnabled = false;
worker.RunWorkerAsync();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
int passo = 0;
// Ciclo di logica
for (passo=1; passo<10; passo++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
// cancello il record -> la Datagrid NON si aggiorna !!
dati1.DelRec(passo);
System.Threading.Thread.Sleep(1000);
}
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Canc1.IsEnabled = true; Canc2.IsEnabled = true; Canc3.IsEnabled = true;
}
private void Canc3_Click(object sender, RoutedEventArgs e)
{
this.timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
timer.Tick += new EventHandler(timer_Tick);
passoT = 1;
Canc1.IsEnabled = false; Canc2.IsEnabled = false; Canc3.IsEnabled = false;
timer.IsEnabled = true;
}
private void timer_Tick(object sender, EventArgs e)
{
// cancello il record -> la Datagrid si aggiorna correttamente
dati1.DelRec(passoT++);
if (passoT>=10)
{
this.timer.IsEnabled = false;
this.timer = null;
Canc1.IsEnabled = true; Canc2.IsEnabled = true; Canc3.IsEnabled = true;
}
}
int passoT;
}
Torna su
Stanze Forum
Elenco Threads
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?
Dopo esserti registrato potrai chiedere
aiuto sul nostro
Forum
oppure aiutare gli altri
Consulta le
Stanze
disponibili.
Registrati ora !