I'm working on a Windows Forms app, Visual Studio 2015. The scenario is that I have a DataGridView where I will enter items to a Detail, I will enter data from a product of a range of sizes that are worth a price, and the same product I will enter it with another range of sizes that are worth another price, so I need to enter the same product more than once.
For this I have implemented a temporary DataTable given the code:
public class DetalleCompraRepository
{
private DataTable _detalleTemp = new DataTable();
public DetalleCompraRepository()
{
_detalleTemp = new DataTable("_detalleTemp");
DataColumn colId = new DataColumn();
colId.DataType = System.Type.GetType("System.Int32");
colId.AutoIncrement = true;
colId.AutoIncrementSeed = 1;
colId.AutoIncrementStep = 1;
_detalleTemp.Columns.Add("colId", typeof(int));
_detalleTemp.PrimaryKey = new DataColumn[] { _detalleTemp.Columns[0] };
_detalleTemp.Columns.Add("ProductoId", typeof(int));
_detalleTemp.Columns.Add("Descripcion", typeof(string));
_detalleTemp.Columns.Add("Cantidad", typeof(int));
_detalleTemp.Columns.Add("Precio", typeof(decimal));
_detalleTemp.Columns.Add("Importe", typeof(decimal), "(Precio * Cantidad)");
}
public DataTable PDetalleTemp
{
get { return _detalleTemp; }
}
public void Agregar(DetalleCompra entity)
{
var fila = _detalleTemp.Rows.Find(entity.DetalleCompraId);
if (fila == null)
{
fila = _detalleTemp.NewRow();
fila["colId"] = entity.DetalleCompraId;
fila["ProductoId"] = entity.ProductoId;
fila["Descripcion"] = entity.Descripcion;
fila["Cantidad"] = entity.Cantidad;
fila["Precio"] = entity.Precio;
fila["Importe"] = entity.Total;
_detalleTemp.Rows.Add((fila));
}
}
}
The DataTable asks me for a pk, which I put it on but, it does not allow me to enter the same id, so I need to put a pk identity to allow me to enter the same item. I've tried this part of code:
DataColumn colId = new DataColumn();
colId.DataType = System.Type.GetType("System.Int32");
colId.AutoIncrement = true;
colId.AutoIncrementSeed = 1;
colId.AutoIncrementStep = 1;
_detalleTemp.Columns.Add("colId", typeof(int));
_detalleTemp.PrimaryKey = new DataColumn[] { _detalleTemp.Columns[0] };
If I can enter a first item, but when I try to enter a second item, in the Add method, you no longer enter the condition if (fila == null)
and that indicates which row is not null.
The way I add the items is as follows:
private void button1_Click(object sender, EventArgs e)
{
var entity = new DetalleCompra()
{
ProductoId = Convert.ToInt32(txtProductoId.Text),
Descripcion = txtDescripcion.Text,
Cantidad = Convert.ToInt32(txtCantidad.Text),
Precio = Convert.ToDecimal(txtPrecio.Text)
};
_detalleCompra.Agregar(entity);
dgvDetalle.AutoGenerateColumns = false;
dgvDetalle.DataSource = _detalleCompra.PDetalleTemp;
}
What I need to know is: