How to edit data (just numbers) and calculate their values on a Datagrid?

Asked

Viewed 283 times

6

I need a Datagrid column to receive from users only numbers in rows (cells) and that after clicking the button, multiplication calculations are performed between cells of the same row and different columns. Datagrid is populated as follows by the class below through the LINQ tool... The users column is "Number Stops", it needs to be multiplied by the column "Time (min)".

But the values the user enters in the cells do not remain in them, what is typed is disappearing. Once it leaves the cell the value is deleted, because?

And as for the logic of calculus I’m only able to add up the cells of a column.

Who can help thank you. Below I put the sequence of commands...

LINQ class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TRSSystem.AcessoDados
{
    public class tabMaquinaParadaAcesso
    {
//Consultar pela MAQUINA no Banco pela estrutura LINQ TO SQL Server
        public static List<tabMaquinaParada> Consultar_OnlyMaquina(string pMaquina, string pTipo)
        {
            TRSSystemDataClassesDataContext oDB = new TRSSystemDataClassesDataContext();
            List<tabMaquinaParada> aMaquina = (from Selecao in oDB.tabMaquinaParadas where Selecao.Maquina == pMaquina && Selecao.Sacaria == pTipo select Selecao).ToList<tabMaquinaParada>();
            return aMaquina;

        }

    }
}

XMAL:

<DataGrid x:Name="dataGridPrdMaquina_ApontPrd" ItemsSource="{Binding}" HorizontalAlignment="Left" Margin="4,7,0,0" VerticalAlignment="Top" Height="103" Width="577" GridLinesVisibility="Horizontal" SelectionUnit="Cell" VerticalContentAlignment="Center" AutoGenerateColumns="False" SelectionMode="Single" AlternatingRowBackground="{DynamicResource SelectedBackgroundBrush}" HorizontalGridLinesBrush="{DynamicResource MouseOverBrush}" VerticalGridLinesBrush="{DynamicResource MouseOverBrush}" HorizontalContentAlignment="Center">
    <DataGrid.Columns>
              <DataGridTextColumn Header="Código" Width="Auto" Binding={Binding CodigoParada}" IsReadOnly="True"/>
              <DataGridTextColumn Header="Descrição da Parada" Width="Auto" Binding="{Binding DescricaoParada}" IsReadOnly="True"/>
              <DataGridTextColumn Header="Tempo (min)" Width="Auto" Binding="{Binding TempoParada}" IsReadOnly="True"/>
              <DataGridTextColumn Header="Tipo" Width="Auto" Binding="{Binding TipoParada}" IsReadOnly="True"/>
              <DataGridTextColumn Header="Nº Paradas" Width="Auto" IsReadOnly="False" FontFamily="Calibri"> 
                                   <DataGridTextColumn.EditingElementStyle>
                                                <Style TargetType="TextBox">
                                                    <Setter Property="MaxLength" Value="2"/>
                                                </Style>
                                            </DataGridTextColumn.EditingElementStyle>
                                        </DataGridTextColumn>
                                    </DataGrid.Columns>
                                </DataGrid>

Lostfocus event from a Combox, when loading the list:

private void CarregarParadas_ApontaPrd(object sender, RoutedEventArgs e)
        {
            try
            {
               dataGridPrdMaquina_ApontPrd.ItemsSource = TRSSystem.AcessoDados.tabMaquinaParadaAcesso.Consultar_OnlyMaquina(CmBox_MaquinaApontaPrd.Text, CmBox_TipoApontaPrd.Text);
            }
            catch(Exception error)
            {
                MessageBox.Show("Erro de Compilação, contacte o Administrador do Sistema." + error, "Erro de Compilação", MessageBoxButton.OK, MessageBoxImage.Error);
            }


        }

Previewtextinput Event - Receive Integers Only

private void SomenteInt_ListViewPrdPadrao_ApontaPrd(object sender, TextCompositionEventArgs e)
        {
            if (!char.IsDigit(e.Text, e.Text.Length - 1))
                e.Handled = true;
        }

Calculus Button

inserir a descrição da imagem aqui

How do I multiply the values of the Time column by the Number Stops?

//Aqui apenas Soma os valores de uma coluna apenas:
 private void CalcularTempoEfetivo_ApontPrd(object sender, RoutedEventArgs e)
        {

            int somarColuna = 0;

            for (int i = 0; i < dataGridPrdMaquina_ApontPrd.Items.Count; i++)
            {

                tabMaquinaParada Dados = (tabMaquinaParada)dataGridPrdMaquina_ApontPrd.Items[i];

                somarColuna = somarColuna + Dados.TempoParada;

            }

            txtTempoEfetivo_ApontaPrd.Text = Convert.ToString(somarColuna);

        }

1 answer

2


The problem is that you need to make Binding with a property.

How you are using a Linq class create a column in the table tabMaquinaParada only for the system to accept this new field.*

  • This operation is not the best.

Table

Create the field NroParada as a whole;

Desing

In the class desing TRSSystemDataClasses include the new field.

Datagrid

And in the datagrid number of stops makes Binding:

<DataGridTextColumn Header="Nº Paradas" Width="Auto" IsReadOnly="False" FontFamily="Calibri" Binding="{Binding NroParada}">...</DataGridTextColumn >

Calculate

And with that you end up solving your 2 question:

    private void CalcularTempoEfetivo_ApontPrd(object sender, RoutedEventArgs e)
    {

        int somarColuna = 0;

        for (int i = 0; i < dataGridPrdMaquina_ApontPrd.Items.Count-1; i++)
        {

            tabMaquinaParada Dados = (tabMaquinaParada)dataGridPrdMaquina_ApontPrd.Items[i];

            somarColuna = somarColuna + (Dados.TempoParada*Dados.NroParada );

        }

        txtTempoEfetivo_ApontaPrd.Text = Convert.ToString(somarColuna);

    }

It is necessary to make dataGridPrdMaquina_ApontPrd.Items.Count-1 because the system brings a blank line, if it does not do so the system accuses error when converting.

  • Thanks for your help... There was an error: An unhandled Exception of type 'System.Invalidoperationexception' occurred in Presentationframework.dll Additional information: Bidirectional association requires Path or Xpath.

  • Something with Binding I believe... And Data.Nroparada also did not work, he did not recognize as column.

  • 1

    You created the property NroParada in class tabMaquinaParada?

  • That’s... Right there!

  • 1

    The error was why he did not find the property in the class... In the code you can find the property NroParada?

  • Neither... Nor in Data.

  • 1

    Strange, I used exactly this example and it worked here... You can post the class code tabMaquinaParada?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.