Usuário com melhor resposta
Persistir valores no submit no item template da gridview

Pergunta
-
Olá pessoal...
Seguinte, eu tenho uma gridview onde são inseridos alguns valores, nas colunas onde eles são inseridos existe um ITEMTEMPLATE e nele o TEXTBOX, porém quando eu processo a leitura da gridiview ele sempre pega os valores vindos inicialmente do banco para esse TEXTBOX e não os que acabei de informar.
Sendo que esse TEXTBOX é renderizado no estado normal, essa minha gridview não tem estado de insert ou edição.Para percorrer a gridview eu faço assim:
For Each g As GridViewRow In gdvParcelamento.Rows
If g.RowType = DataControlRowType.DataRow Then
Dim valorParcela As TextBox = g.FindControl("textValorParcela")
Msgbox(valorParcela)End If
Next
desde já, agradeço a ajuda.
João Batista :: MSN jbdiacompleto@hotmail.com :: http://www.hostmundo.com.br/hospedagem.php
Respostas
-
Segue um exemplo onde carrego um GridView de acordo com o DropDownList. Coloquei um button para pegar as
informações de to
das as linhas do Contnrole. O TextBox é fica dentro de um TemplateColumn.
ps: fiz o exemplo em csharp. Estou colocando o somente o .cs convertido em VB.NET
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public class Evento { public int CODIGO { get; set; } public string DESC { get; set; } public DateTime? DATA { get; set; } public static List<evento> GetListaDeEventos() { List<evento> lstEventos = new List<evento>() { new Evento(){ CODIGO = 1, DESC = "", DATA = DateTime.Now}, new Evento(){ CODIGO = 2, DESC = "", DATA = DateTime.Now}, new Evento(){ CODIGO = 3, DESC = "", DATA = DateTime.Now} }; return lstEventos; } } public partial class GridViewList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { TextBox1.Text = string.Empty; if (DropDownList1.SelectedValue.Equals("Sim")) { var retorno = Evento.GetListaDeEventos(); GridView1.DataSource = retorno; GridView1.DataBind(); } else { GridView1.DataSource = null; GridView1.DataBind(); } } protected void btnSelecionar_Click(object sender, EventArgs e) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (GridViewRow row in GridView1.Rows) { string codigoText = row.Cells[0].Text; string dataText = row.Cells[2].Text; TextBox txtDescEvento = row.FindControl("txtEvento") as TextBox; sb.AppendLine(string.Format("Codigo {0} ", codigoText)); sb.AppendLine(string.Format("Evento: {0} ", txtDescEvento.Text)); sb.AppendLine(string.Format("Data: {0}", dataText)); sb.AppendLine("- - - - - - - - - - - - - - -"); } TextBox1.Text = sb.ToString(); } }</evento></evento></evento>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewList.aspx.cs" Inherits="GridViewList" %> <form id="form1" runat="server">
Deseja carregar o controle? <asp:dropdownlist autopostback="True" id="DropDownList1" onselectedindexchanged="DropDownList1_SelectedIndexChanged" runat="server"> <asp:listitem selected="selected" value="Nao">Não</asp:listitem> <asp:listitem>Sim</asp:listitem> </asp:dropdownlist>
<asp:gridview autogeneratecolumns="False" id="GridView1" runat="server"> <columns> <asp:boundfield datafield="CODIGO" headertext="Codigo"></asp:boundfield> <asp:templatefield headertext="Evento"> <itemtemplate> <asp:textbox id="txtEvento" runat="server"></asp:textbox> </itemtemplate> </asp:templatefield> <asp:boundfield datafield="DATA" headertext="Data"></asp:boundfield> </columns> </asp:gridview><asp:button id="btnSelecionar" onclick="btnSelecionar_Click" runat="server" text="Pegar Informações"></asp:button>
<asp:textbox height="258px" id="TextBox1" runat="server" textmode="MultiLine" width="481px"></asp:textbox>
</form>
VB
Imports System.Collections.Generic Imports System.Linq Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Public Class Evento Public Property CODIGO() As Integer Get Return m_CODIGO End Get Set m_CODIGO = Value End Set End Property Private m_CODIGO As Integer Public Property DESC() As String Get Return m_DESC End Get Set m_DESC = Value End Set End Property Private m_DESC As String Public Property DATA() As System.Nullable(Of DateTime) Get Return m_DATA End Get Set m_DATA = Value End Set End Property Private m_DATA As System.Nullable(Of DateTime) Public Shared Function GetListaDeEventos() As List(Of Evento) Dim lstEventos As New List(Of Evento)() From { _ New Evento() With { _ Key .CODIGO = 1, _ Key .DESC = "", _ Key .DATA = DateTime.Now _ }, _ New Evento() With { _ Key .CODIGO = 2, _ Key .DESC = "", _ Key .DATA = DateTime.Now _ }, _ New Evento() With { _ Key .CODIGO = 3, _ Key .DESC = "", _ Key .DATA = DateTime.Now _ } _ } Return lstEventos End Function End Class Public Partial Class GridViewList Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) End Sub Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) TextBox1.Text = String.Empty If DropDownList1.SelectedValue.Equals("Sim") Then Dim retorno = Evento.GetListaDeEventos() GridView1.DataSource = retorno GridView1.DataBind() Else GridView1.DataSource = Nothing GridView1.DataBind() End If End Sub Protected Sub btnSelecionar_Click(sender As Object, e As EventArgs) Dim sb As New System.Text.StringBuilder() For Each row As GridViewRow In GridView1.Rows Dim codigoText As String = row.Cells(0).Text Dim dataText As String = row.Cells(2).Text Dim txtDescEvento As TextBox = TryCast(row.FindControl("txtEvento"), TextBox) sb.AppendLine(String.Format("Codigo {0} ", codigoText)) sb.AppendLine(String.Format("Evento: {0} ", txtDescEvento.Text)) sb.AppendLine(String.Format("Data: {0}", dataText)) sb.AppendLine("- - - - - - - - - - - - - - -") Next TextBox1.Text = sb.ToString() End Sub End Class
Paulo César Viana
.NET Developer
MCC - Microsoft Community Contributor
MCP - Microsoft Certified Professional
MCTS - Microsoft Certified Technology Especialist
--
Marque as respostas e contribua para uma melhora no fórum.- Editado Paulo César Viana terça-feira, 7 de fevereiro de 2012 16:26 anexar imagem
- Marcado como Resposta Harley Araujo quinta-feira, 9 de fevereiro de 2012 11:37
Todas as Respostas
-
João,
No RowDataBound o controle ainda está sendo renderizado, logo os valores que você vai ter no controle após o Bind é justamente aqueles que vieram da fonte de dados. Você deve recuperar as informações em outro momento.
O ideal é que você tenha um button para fazer atal ação. Com isto você pode fazer assim:
For Each row As GridViewRow In GridView1.Rows If row.RowType = DataControlRowType.DataRow Then Dim txt As TextBox = DirectCast(row.FindControl("SeuControle"), TextBox) Dim texto As String = txt.Text End If Next
Isto vai garantir que você pegue tudo o que tem no controle (GridView.Rows).
Paulo César Viana
.NET Developer
MCC - Microsoft Community Contributor
MCP - Microsoft Certified Professional
MCTS - Microsoft Certified Technology Especialist
--
Marque as respostas e contribua para uma melhora no fórum.- Editado Paulo César Viana terça-feira, 7 de fevereiro de 2012 11:37
-
Oi Paulo... então, eu realmente estou colocando essa leitura em button, o problema é que ele está pegando valores vindo do banco, ou seja, ele dá bind novamente e não pega o valor que alterei no TEXTBOX, o jeito que passou é a maneria que estou fazendo... e mesmo assim pega o valor do banco e não o valor que acabei de alterar... eu preciso pegar o valor não do datasource inicialmente carregado na gridview mas os novos valores digitados na gridview...
João Batista :: MSN jbdiacompleto@hotmail.com :: http://www.hostmundo.com.br/hospedagem.php
-
João,
No PageLoad você valida se é PostBack para poder fazer a carga do GridView?
Pode ser que você não esteja validando e com isto sempre carrega o controle no PostBack.
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //carrega seu GridView } }
Paulo César Viana
.NET Developer
MCC - Microsoft Community Contributor
MCP - Microsoft Certified Professional
MCTS - Microsoft Certified Technology Especialist
--
Marque as respostas e contribua para uma melhora no fórum. -
Então, realmente não valida, mas daí há uma dúvida, o bind nessa gridview não é feito no pageLoad, mas por um evento change de um controle dentro da minha página, esse evento dá bind nessa minha gridview quando acionado, mas quando eu aciono o submit que lê essa gridview ele dá bind novamente, para isso não ocorrer é também necessário colocar o método que executa o bind na gridview dentro PostBack?
Ex:
if (!IsPostBack) {meuMetodoBindGridview(); }
João Batista :: MSN jbdiacompleto@hotmail.com :: http://www.hostmundo.com.br/hospedagem.php
-
Se você fizer isto o controle não vai ser carregado.
Veja que o problema é justamente o que Imaginei. Seu controle é carregado no PostBack por isto você perde as informações e fica somente com as do Banco. Não tem como carregar o controle em outro momento? Ou então validar para saber que o controle já foi carregado?
Por qual motivo você usa o evento change?? As vezes você precisa disto. Neste caso teremos que encontrar outra solução. Vou ver aqui.Paulo César Viana
.NET Developer
MCC - Microsoft Community Contributor
MCP - Microsoft Certified Professional
MCTS - Microsoft Certified Technology Especialist
--
Marque as respostas e contribua para uma melhora no fórum. -
Esse evento change é acionado em um AutoPostBack de um droplist, ele passa um parametro que é necessário para eu dar bind na minha gridview e depois tem o button que aciona a leitura dessa gridview quando clicado e aí que ocorre o bind novamente (que não deveria, mas sim, pegar os dados digitados nas linhas da gridview).
João Batista :: MSN jbdiacompleto@hotmail.com :: http://www.hostmundo.com.br/hospedagem.php
-
Neste caso não é para ter problemas. Vou fazer um exemplo para você ver.
Antes disto me responda uma coisa: você usa o evento SelectedIndexChanged correto?
Paulo César Viana
.NET Developer
MCC - Microsoft Community Contributor
MCP - Microsoft Certified Professional
MCTS - Microsoft Certified Technology Especialist
--
Marque as respostas e contribua para uma melhora no fórum.- Editado Paulo César Viana terça-feira, 7 de fevereiro de 2012 15:24
-
Segue um exemplo onde carrego um GridView de acordo com o DropDownList. Coloquei um button para pegar as
informações de to
das as linhas do Contnrole. O TextBox é fica dentro de um TemplateColumn.
ps: fiz o exemplo em csharp. Estou colocando o somente o .cs convertido em VB.NET
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public class Evento { public int CODIGO { get; set; } public string DESC { get; set; } public DateTime? DATA { get; set; } public static List<evento> GetListaDeEventos() { List<evento> lstEventos = new List<evento>() { new Evento(){ CODIGO = 1, DESC = "", DATA = DateTime.Now}, new Evento(){ CODIGO = 2, DESC = "", DATA = DateTime.Now}, new Evento(){ CODIGO = 3, DESC = "", DATA = DateTime.Now} }; return lstEventos; } } public partial class GridViewList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) { TextBox1.Text = string.Empty; if (DropDownList1.SelectedValue.Equals("Sim")) { var retorno = Evento.GetListaDeEventos(); GridView1.DataSource = retorno; GridView1.DataBind(); } else { GridView1.DataSource = null; GridView1.DataBind(); } } protected void btnSelecionar_Click(object sender, EventArgs e) { System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (GridViewRow row in GridView1.Rows) { string codigoText = row.Cells[0].Text; string dataText = row.Cells[2].Text; TextBox txtDescEvento = row.FindControl("txtEvento") as TextBox; sb.AppendLine(string.Format("Codigo {0} ", codigoText)); sb.AppendLine(string.Format("Evento: {0} ", txtDescEvento.Text)); sb.AppendLine(string.Format("Data: {0}", dataText)); sb.AppendLine("- - - - - - - - - - - - - - -"); } TextBox1.Text = sb.ToString(); } }</evento></evento></evento>
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridViewList.aspx.cs" Inherits="GridViewList" %> <form id="form1" runat="server">
Deseja carregar o controle? <asp:dropdownlist autopostback="True" id="DropDownList1" onselectedindexchanged="DropDownList1_SelectedIndexChanged" runat="server"> <asp:listitem selected="selected" value="Nao">Não</asp:listitem> <asp:listitem>Sim</asp:listitem> </asp:dropdownlist>
<asp:gridview autogeneratecolumns="False" id="GridView1" runat="server"> <columns> <asp:boundfield datafield="CODIGO" headertext="Codigo"></asp:boundfield> <asp:templatefield headertext="Evento"> <itemtemplate> <asp:textbox id="txtEvento" runat="server"></asp:textbox> </itemtemplate> </asp:templatefield> <asp:boundfield datafield="DATA" headertext="Data"></asp:boundfield> </columns> </asp:gridview><asp:button id="btnSelecionar" onclick="btnSelecionar_Click" runat="server" text="Pegar Informações"></asp:button>
<asp:textbox height="258px" id="TextBox1" runat="server" textmode="MultiLine" width="481px"></asp:textbox>
</form>
VB
Imports System.Collections.Generic Imports System.Linq Imports System.Web Imports System.Web.UI Imports System.Web.UI.WebControls Public Class Evento Public Property CODIGO() As Integer Get Return m_CODIGO End Get Set m_CODIGO = Value End Set End Property Private m_CODIGO As Integer Public Property DESC() As String Get Return m_DESC End Get Set m_DESC = Value End Set End Property Private m_DESC As String Public Property DATA() As System.Nullable(Of DateTime) Get Return m_DATA End Get Set m_DATA = Value End Set End Property Private m_DATA As System.Nullable(Of DateTime) Public Shared Function GetListaDeEventos() As List(Of Evento) Dim lstEventos As New List(Of Evento)() From { _ New Evento() With { _ Key .CODIGO = 1, _ Key .DESC = "", _ Key .DATA = DateTime.Now _ }, _ New Evento() With { _ Key .CODIGO = 2, _ Key .DESC = "", _ Key .DATA = DateTime.Now _ }, _ New Evento() With { _ Key .CODIGO = 3, _ Key .DESC = "", _ Key .DATA = DateTime.Now _ } _ } Return lstEventos End Function End Class Public Partial Class GridViewList Inherits System.Web.UI.Page Protected Sub Page_Load(sender As Object, e As EventArgs) End Sub Protected Sub DropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) TextBox1.Text = String.Empty If DropDownList1.SelectedValue.Equals("Sim") Then Dim retorno = Evento.GetListaDeEventos() GridView1.DataSource = retorno GridView1.DataBind() Else GridView1.DataSource = Nothing GridView1.DataBind() End If End Sub Protected Sub btnSelecionar_Click(sender As Object, e As EventArgs) Dim sb As New System.Text.StringBuilder() For Each row As GridViewRow In GridView1.Rows Dim codigoText As String = row.Cells(0).Text Dim dataText As String = row.Cells(2).Text Dim txtDescEvento As TextBox = TryCast(row.FindControl("txtEvento"), TextBox) sb.AppendLine(String.Format("Codigo {0} ", codigoText)) sb.AppendLine(String.Format("Evento: {0} ", txtDescEvento.Text)) sb.AppendLine(String.Format("Data: {0}", dataText)) sb.AppendLine("- - - - - - - - - - - - - - -") Next TextBox1.Text = sb.ToString() End Sub End Class
Paulo César Viana
.NET Developer
MCC - Microsoft Community Contributor
MCP - Microsoft Certified Professional
MCTS - Microsoft Certified Technology Especialist
--
Marque as respostas e contribua para uma melhora no fórum.- Editado Paulo César Viana terça-feira, 7 de fevereiro de 2012 16:26 anexar imagem
- Marcado como Resposta Harley Araujo quinta-feira, 9 de fevereiro de 2012 11:37