Autor
|
Tema: DUDA ASP.NET C# (Leído 4,044 veces)
|
Yaldabaot
Desconectado
Mensajes: 186
|
Buenas Estoy tratando de hacer algo muy simple, es solo agregar al datagridview un registro conforme voy dandole los datos y posteriormente multiplicar y sumar las facturas, tal como se hace cuando uno realiza un facturador. //DataTable dt = new DataTable(); //dt.Columns.Add("Codigo_Articulo"); //dt.Columns.Add("Descripcion"); //dt.Columns.Add("Cantidad"); //dt.Columns.Add("Precio"); DataTable dt = dgvCostos.DataSource as DataTable; if (dt != null) { DataRow dr = dt.NewRow(); dr["Codigo_Articulo"] = txtCodArt.Text; dr["Descripcion"] = txtDescripcion.Text; dr["Cantidad"] = txtCantidad.Text; dr["Precio"] = txtPrecio.Text; dt.Rows.Add(dr); dt.AcceptChanges(); dgvCostos.DataSource = dt; dgvCostos.DataBind(); }
Estoy con ese codigo, pero simplemente no hace nada, como pueden ver lo he alternado, pero simplemente el datagridview sigue viendose vacio. En el datagridview tengo realizado las columnas respectivas(ya estan creadas), pero bueno sigo sin entender el porque no se agregan con un codigo tan simple. Y de paso, saben como puedo hacer que conforme se agregue se multipliquen la columna precio * cantidad?, y al final sumarlos todos como en una factura?. Estuve pensando que usando alguno de los parametros e que capturan los eventos se puede realizar, pero talvez haya una forma mas simple. Estoy trabajando con visual studio 2010, ASP.NET C#. De antemano gracias al menos por leerme.
|
|
|
En línea
|
Nunca me contestan -_-
|
|
|
|
Eleкtro
Ex-Staff
Desconectado
Mensajes: 9.818
|
Buenas. No manejo ASP.Net, ni tampoco tengo muy claro si esto es lo que andas buscando, pero he intentado reproducir el problema que tienes en tecnología WinForms. Mira a ver si el siguiente source te resuelve todas o al menos alguna de tus dudas... Para las operaciones artiméticas he recurrido a LINQ ya que se puede utilizar de forma "global". Descarga del proyecto: https://www.mediafire.com/?y1yifofj0s8i6r8VB.Net:Public Class Form1 Private WithEvents dt As DataTable Private ReadOnly columns As DataColumn() = { New DataColumn("Codigo_Articulo", GetType(String)), New DataColumn("Descripcion", GetType(String)), New DataColumn("Cantidad", GetType(Integer)), New DataColumn("Precio", GetType(Decimal)) } ' añadir fila Private Sub Button_añadir_Click() Handles Button_añadir.Click If dt Is Nothing Then dt = New DataTable dt.Columns.AddRange(columns) dgvCostos.DataSource = dt ' dgvCostos.DataBind() End If Dim dr As DataRow = dt.NewRow() dr(columns(0)) = txtCodArt.Text dr(columns(1)) = txtDescripcion.Text dr(columns(2)) = txtCantidad.Text dr(columns(3)) = txtPrecio.Text dt.Rows.Add(dr) dt.AcceptChanges() End Sub ' Sumar y Multiplicar Private Sub Button_sumar_Click(sender As Object, e As EventArgs) Handles Button_sumar.Click ' total de cantidades Dim sumaCantidades As Integer = (From row As DataRow In dt.Rows Select CType(row.Item(2I), Integer)).Sum ' total de precios Dim sumaPrecios As Integer = (From row As DataRow In dt.Rows Select CType(row.Item(3I), Integer)).Sum ' un type anónimo, el cual contiene cada DataRow, y cada "cantidad * precio" de cada DataRow. Dim multi = From row As DataRow In dt.Rows Let multiply As Integer = CType(row.Item(2I), Integer) * CType(row.Item(3I), Integer) Dim sb As New System.Text.StringBuilder sb.AppendLine(String.Format("Cantidad total: {0}", CStr(sumaCantidades))) sb.AppendLine(String.Format("Precio total: {0}", CStr(sumaPrecios))) sb.AppendLine() For index As Integer = 0 To (multi.Count - 1) sb.AppendLine(String.Format("Row: {0}, Cantidad: {1}, Precio: {2}, Precio total: {3}", CStr(index), CStr(multi(index).row.Item(2I)), CStr(multi(index).row.Item(3I)), CStr(multi(index).multiply))) Next index MessageBox.Show(sb.ToString) End Sub End Class
C# (traducción online)using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; public class Form1 { private DataTable dt; private readonly DataColumn[] columns = { new DataColumn ("Codigo_Articulo", typeof(string)), new DataColumn ("Descripcion", typeof(string)), }; // añadir fila private void Button_añadir_Click() { this.dt = (DataTable)dgvCostos.DataSource; if (dt == null) { dt.Columns.AddRange(columns); dgvCostos.DataSource = dt; // dgvCostos.DataBind() } DataRow dr = dt.NewRow(); dr(columns(0)) = txtCodArt.Text; dr(columns(1)) = txtDescripcion.Text; dr(columns(2)) = txtCantidad.Text; dr(columns(3)) = txtPrecio.Text; dt.Rows.Add(dr); dt.AcceptChanges(); } // Sumar y Multiplicar private void Button_sumar_Click(object sender, EventArgs e) { // total de cantidades int sumaCantidades = (from row in dt.RowsConvert.ToInt32(row.Item(2))).Sum; // total de precios int sumaPrecios = (from row in dt.RowsConvert.ToInt32(row.Item(3))).Sum; // un type anónimo, el cual contiene cada DataRow, y cada "cantidad * precio" de cada DataRow. dynamic multi = from row in dt.RowsConvert.ToInt32(row.Item(2)) * Convert.ToInt32(row.Item(3))int; System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendLine(string.Format("Cantidad total: {0}", Convert.ToString(sumaCantidades))); sb.AppendLine(string.Format("Precio total: {0}", Convert.ToString(sumaPrecios))); sb.AppendLine(); for (int index = 0; index <= (multi.Count - 1); index++) { sb.AppendLine(string.Format("Row: {0}, Cantidad: {1}, Precio: {2}, Precio total: {3}", Convert.ToString(index), Convert.ToString(multi(index).row.Item(2)), Convert.ToString(multi(index).row.Item(3)), Convert.ToString(multi(index).multiply))); } MessageBox.Show(sb.ToString); } } //======================================================= //Service provided by Telerik (www.telerik.com) //Conversion powered by NRefactory. //Twitter: @telerik //Facebook: facebook.com/telerik //=======================================================
|
|
« Última modificación: 12 Noviembre 2014, 20:08 pm por Eleкtro »
|
En línea
|
|
|
|
Yaldabaot
Desconectado
Mensajes: 186
|
Gracias elektro!!!, lo probaré y te cuento como me fue!!!
SALUDOS!!.
|
|
|
En línea
|
Nunca me contestan -_-
|
|
|
Yaldabaot
Desconectado
Mensajes: 186
|
Lamento decirlo, pero sigo sin poder agregarlos, el datagrid sigue en blanco, será algún postback o alguna propiedad(le cambie los parentesis por cuadrados porque me daba error, pero lo demás estaba idéntico). //Codigo del botón this.dt = (DataTable)dgvCostos.DataSource; if (dt == null) { dt = new DataTable(); dt.Columns.AddRange(columns); dgvCostos.DataSource = dt; dgvCostos.DataBind(); } / DataRow dr = dt.NewRow(); dr["Codigo_Articulo"] = txtCodArt.Text; dr["Descripcion"] = txtDescripcion.Text; dr["Cantidad"] = txtCantidad.Text; dr["Precio"] = txtPrecio.Text; dt.Rows.Add(dr); dt.AcceptChanges(); } //Codigo del datatable private DataTable dt; private readonly DataColumn[] columns = { new DataColumn("Codigo_Articulo", typeof(string)), new DataColumn("Descripcion", typeof(string)), new DataColumn("Cantidad", typeof(int)), new DataColumn("Precio", typeof(double)) };
|
|
|
En línea
|
Nunca me contestan -_-
|
|
|
Yaldabaot
Desconectado
Mensajes: 186
|
Estoy usando este otro código y el gridview ni se inmuta D: DataTable dt; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { dt = new DataTable(); MakeDataTable(); } else { dt = (DataTable)ViewState["DataTable"]; } ViewState["DataTable"] = dt; } protected void btnAgregar_Click(object sender, EventArgs e) { AddToDataTable(); BindGrid(); } private void MakeDataTable() { dt.Columns.Add("Codigo_Articulo"); dt.Columns.Add("Descripcion"); dt.Columns.Add("Cantidad"); dt.Columns.Add("Precio"); } private void AddToDataTable() { DataRow dr = dt.NewRow(); dr["Codigo_Articulo"] = txtCodArt.Text; dr["Descripcion"] = txtDescripcion.Text; dr["Cantidad"] = txtCantidad.Text; dr["Precio"] = txtPrecio.Text; dt.Rows.Add(dr); } private void BindGrid() { dgvCostos.DataSource = dt; dgvCostos.DataBind(); }
|
|
|
En línea
|
Nunca me contestan -_-
|
|
|
Yaldabaot
Desconectado
Mensajes: 186
|
Nadie sabe?
Ayuda alguien u.u?, no entiendo porque no he podido.
|
|
« Última modificación: 15 Noviembre 2014, 22:00 pm por Yaldabaot »
|
En línea
|
Nunca me contestan -_-
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Pequeña duda con un comando batch (NUEVA DUDA RELACIONADA)
Scripting
|
revenge1252
|
9
|
9,752
|
13 Febrero 2008, 21:41 pm
por revenge1252
|
|
|
Duda duda y duda de Metasploit
Bugs y Exploits
|
huber_nomas
|
4
|
5,785
|
17 Febrero 2012, 14:00 pm
por MauroMasciar
|
|
|
Duda facil, [VIDEO QUE EXPLICA MI DUDA]
Diseño Gráfico
|
Ngeooz
|
6
|
8,866
|
2 Diciembre 2013, 19:33 pm
por Ngeooz
|
|
|
[DUDA] Cambiar letra de unidad a archivo con un Batch [DUDA]
« 1 2 »
Windows
|
MrMaticool
|
10
|
11,320
|
12 Febrero 2014, 17:55 pm
por MrMaticool
|
|
|
[DUDA][LICENCIA][GPL]tengo una duda sobre las caracteristicas de la licencia GPL
Dudas Generales
|
Noxware
|
0
|
1,870
|
2 Mayo 2014, 00:34 am
por Noxware
|
|