Update my DataGrid in C # without using buttons

0

I tell you I am trying to update my datagrid without the need to give any button. This datagrid is filled by making calls to a database. It had occurred to me to use threads for in the background to update the calls every so often as if it were a screen refresh time.

    private void recargar()
    {
        while (true)
        {
            DataTable dt = new DataTable();
            dt = getconnection();
            dataGrid1.ItemsSource = dt.DefaultView;
            Thread.Sleep(3000);
        }
    }

The problem is that this way or creating a new thread never ends and does not take out the table (the interface), it remains in constant execution. So my question is that how can I do from the main call to reload and make the thread without preventing the table from coming out and thus changing the values of the table from time to time.

already someone knows how I can do to fit the text to the size of the datagrid?

    
asked by Luis Dominguez 20.03.2018 в 20:26
source

2 answers

2

In the event load of your form do this:

Timer actualizar_automatico = new Timer(); 

private void TuForm_Load(object sender, EventArgs e)
{
     //........
     actualizar_automatico.Interval = 3000;
     actualizar_automatico.Tick += actualizar_automatico_Tick;
     actualizar_automatico.Enabled = true; 
}

Your role would be like this:

private void recargar()
{
    DataTable dt = new DataTable();
    dt = getconnection();
    dataGrid1.ItemsSource = dt.DefaultView;
} 

Then there would be the event that will execute the function automatically:

private void actualizar_automatico_Tick(object sender, EventArgs e)
{ 
   recargar(); 
}
    
answered by 20.03.2018 / 20:50
source
2

A thousand thanks to everyone! I've managed to fix it with the Time tool at the end

public MainWindow()
    {
        InitializeComponent();

        DataTable dt = new DataTable();
        dt = getconnection();
        dataGrid1.ItemsSource = dt.DefaultView;
        timer.Tick += new EventHandler(recargar); 
        timer.Interval = (1000) * (1);              
        timer.Enabled = true;                       
        timer.Start();                              
    }
    
answered by 20.03.2018 в 21:04