none
Gridview deleting row mantendo o indice RRS feed

  • Pergunta

  • Ola, estou tentando fazer em um gridview, onde que a ideia é adicionar vários produtos e enviar tudo so de uma vez para o banco de dados, até está parte eu já consegui fazer tranquilamente, o problema maior é que por um exemplo, eu erro o item de uma row dai eu tenho que ter um botão pra excluir esta row, eu fiz o botão delete só que quando eu clico no botão delete é como se ele perde-se todos os índices das row. Quem souber vai salvar minha vida hehe

    codigo em VB.NET:

    Public Class nova_entrada
      Inherits System.Web.UI.Page
    	Dim data As New bd
    	Dim sql As String = ""
    
      Dim rowIndex As Integer = 0
    	Dim rowIndex2 As Integer = 0
    	Dim rowIndex3 As Integer = 0
    
    	Private Sub SetInitialRow()
    		Dim dt As New DataTable()
    		Dim dr As DataRow = Nothing
    		dt.Columns.Add(New DataColumn("Modelo", GetType(String)))
    		dt.Columns.Add(New DataColumn("QTD", GetType(String)))
    		dt.Columns.Add(New DataColumn("Valor", GetType(String)))
    		dr = dt.NewRow()
    		dr("Modelo") = String.Empty
    		dr("QTD") = String.Empty
    		dr("Valor") = String.Empty
    		dt.Rows.Add(dr)
    		ViewState("CurrentTable") = dt
    		Gridview1.DataSource = dt
    		Gridview1.DataBind()
    	End Sub
    
    
    	Private Sub nova_entrada_Load(sender As Object, e As EventArgs) Handles Me.Load
    		If Not Page.IsPostBack Then
    			SetInitialRow()
    		End If
    	End Sub
    
    	Private Sub AddNewRowToGrid()
    
    		Dim rowIndex As Integer = 0
    
    		If ViewState("CurrentTable") IsNot Nothing Then
    			Dim dtCurrentTable As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
    			Dim drCurrentRow As DataRow = Nothing
    
    			If dtCurrentTable.Rows.Count > 0 Then
    				For i As Integer = 1 To dtCurrentTable.Rows.Count
    					Dim box1 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(0).FindControl("TextBox1"), TextBox)
    					Dim box2 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox2"), TextBox)
    					Dim box3 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox3"), TextBox)
    					drCurrentRow = dtCurrentTable.NewRow()
    					dtCurrentTable.Rows(i - 1)("Modelo") = box1.Text
    					dtCurrentTable.Rows(i - 1)("QTD") = box2.Text
    					dtCurrentTable.Rows(i - 1)("Valor") = box3.Text
    					rowIndex += 1
    				Next
    
    				dtCurrentTable.Rows.Add(drCurrentRow)
    				ViewState("CurrentTable") = dtCurrentTable
    				Gridview1.DataSource = dtCurrentTable
    				Gridview1.DataBind()
    
    			End If
    		Else
    			Response.Write("ViewState is null")
    		End If
    		SetPreviousData()
    
    	End Sub
    
      Private Sub SetPreviousData()
    
        If ViewState("CurrentTable") IsNot Nothing Then
          Dim dt As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
          If dt.Rows.Count > 0 Then
            For i As Integer = 0 To dt.Rows.Count - 1
              Dim box1 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(0).FindControl("TextBox1"), TextBox)
              Dim box2 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox2"), TextBox)
              Dim box3 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox3"), TextBox)
              box1.Text = dt.Rows(i)("Modelo").ToString()
              box2.Text = dt.Rows(i)("QTD").ToString()
              box3.Text = dt.Rows(i)("Valor").ToString()
              rowIndex += 1
            Next
          End If
        End If
    
      End Sub
    
      Private Sub SetPreviousData2()
    
        If ViewState("CurrentTable") IsNot Nothing Then
          Dim dt As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
          If dt.Rows.Count > 0 Then
            For i As Integer = 0 To dt.Rows.Count
              Dim box1 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(0).FindControl("TextBox1"), TextBox)
              Dim box2 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(1).FindControl("TextBox2"), TextBox)
              Dim box3 As TextBox = DirectCast(Gridview1.Rows(rowIndex).Cells(2).FindControl("TextBox3"), TextBox)
              box1.Text = dt.Rows(i)("Modelo").ToString()
              box2.Text = dt.Rows(i)("QTD").ToString()
              box3.Text = dt.Rows(i)("Valor").ToString()
              rowIndex += 1
            Next
          End If
        End If
    
      End Sub
    
    	Protected Sub ButtonAdd_Click(sender As Object, e As EventArgs)
    		AddNewRowToGrid()
    	End Sub
    
    	Protected Sub BTN1_Click(sender As Object, e As EventArgs) Handles BTN1.Click
    		Call Inserir()
    	End Sub
    
    	Protected Sub Inserir()
    		'GRAVANDO CABEÇALHO
    		Dim Id_forn As String = data.consultar4("ID_FORN", "NOME = '" + txtfornecedor.Text + "'", "CAD_FORNECEDOR")
    
    		sql = "INSERT INTO EST_ENTRADA_C (ID_FORN,ID_ENTRADA,DOCUMENTO,STATUS,OBS)" & _
    			"VALUES (" + Id_forn + "," + cbmotivo.Text + ",'" + txtdocumento.Text + "','A','" + txtobs.Text + "')"
    		data.inserir(sql, "EST_ENTRADA_C", "ID_FORN = '" + Id_forn + "' AND DOCUMENTO = '" + txtdocumento.Text + "'", Me)
    
    		'GRAVANDO DETALHES
    		Dim Id_nota As String = data.consultar6("ID_NOTA", "EST_ENTRADA_C")
    		Dim Id_produto As String = vbNullString
    		Dim Valor_total As Long = 0
    		Dim dt As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
    		For i As Integer = 0 To dt.Rows.Count - 1
    			Dim box1 As TextBox = DirectCast(Gridview1.Rows(rowIndex3).Cells(0).FindControl("TextBox1"), TextBox)
    			Dim box2 As TextBox = DirectCast(Gridview1.Rows(rowIndex3).Cells(1).FindControl("TextBox2"), TextBox)
    			Dim box3 As TextBox = DirectCast(Gridview1.Rows(rowIndex3).Cells(2).FindControl("TextBox3"), TextBox)
    			Id_produto = data.consultar4("ID", "MODELO = '" + box1.Text + "'", "CAD_PRODUTO")
    			Valor_total = box2.Text * box3.Text
    			sql = "INSERT INTO EST_ENTRADA_D (ID_NOTA,ID_PRODUTO,QTD,VALOR,VALOR_TOTAL)" & _
    			"VALUES (" + Id_nota + "," + Id_produto + "," + box2.Text + "," + Replace(box3.Text, ",", ".") + "," + Valor_total.ToString + ")"
    			data.inserir(sql, "EST_ENTRADA_D", "", Me)
    
    			Dim Est_atual As Long = data.consultar6("EST_ATUAL", "ID_PRODUTO = " + Id_produto, "SYS_ESTOQUE")
    			Est_atual = Est_atual + box2.Text
    			data.atualizar("SYS_ESTOQUE", "EST_ATUAL = EST_ATUAL + " + Est_atual.ToString, "ID_PRODUTO = " + Id_produto)
    
    			rowIndex3 += 1
    		Next
    	End Sub
    
      Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim count As Integer = 0
        Gridview1.DataBind()
        Dim arr As ArrayList = DirectCast(ViewState("SelectedRecords"), ArrayList)
        For i As Integer = 0 To Gridview1.Rows.Count - 1
          If arr.Contains(Gridview1.DataKeys(i).Value) Then
            Gridview1.DeleteRow(Gridview1.DataKeys(i).Value)
            arr.Remove(Gridview1.DataKeys(i).Value)
          End If
        Next
        ViewState("SelectedRecords") = arr
      End Sub
    
    
      Protected Sub OnRowDeleting(sender As Object, e As GridViewDeleteEventArgs)
        Dim index As Integer = Convert.ToInt32(e.RowIndex)
        Dim dt As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
        dt.Rows(index).Delete()
        ViewState("CurrentTable") = dt
        BindGrid()
        SetPreviousData2()
      End Sub
    
      Protected Sub BindGrid()
        Gridview1.DataSource = DirectCast(ViewState("CurrentTable"), DataTable)
        GridView1.DataBind()
      End Sub
    
      Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
        If e.Row.RowType = DataControlRowType.DataRow Then
          Dim item As String = e.Row.Cells(0).Text
          For Each button As Button In e.Row.Cells(2).Controls.OfType(Of Button)()
            If button.CommandName = "Delete" Then
              button.Attributes("onclick") = "if(!confirm('Do you want to delete " + item + "?')){ return false; };"
            End If
          Next
        End If
      End Sub
    
    End Class

    no asp:

        <br />
    		Produtos
        <br />
        <div class="gridview_novo_produto">
    		   <asp:gridview ID="Gridview1" runat="server" CssClass="gridview" ShowFooter="True" AutoGenerateColumns="False" OnRowDeleting="OnRowDeleting" OnRowDataBound = "OnRowDataBound">
            <Columns>
    
    
            <asp:TemplateField HeaderText="" HeaderStyle-CssClass="GridViewHeaderStyle">
                <ItemTemplate>
                  <asp:CheckBox ID="CheckBox1" runat="server"  />
                </ItemTemplate>
    
              <HeaderStyle CssClass="GridViewHeaderStyle"></HeaderStyle></asp:TemplateField>
            <asp:TemplateField HeaderText="Modelo" HeaderStyle-CssClass="GridViewHeaderStyle">
                <ItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server"  ></asp:TextBox>
    							<asp:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="TextBox1" ServicePath="AutoComplete.asmx"  ServiceMethod="GetListaModelo" MinimumPrefixLength="1" CompletionInterval="10" EnableCaching="true" CompletionSetCount="12" />
                </ItemTemplate>
    
    
    <HeaderStyle CssClass="GridViewHeaderStyle"></HeaderStyle>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="QTD" HeaderStyle-CssClass="GridViewHeaderStyle">
                <ItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </ItemTemplate>
    
    <HeaderStyle CssClass="GridViewHeaderStyle"></HeaderStyle>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Valor" HeaderStyle-CssClass="GridViewHeaderStyle">
                <ItemTemplate>
                     <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </ItemTemplate>
                <FooterStyle HorizontalAlign="Right" />
                <FooterTemplate>
                 <asp:Button ID="ButtonAdd" runat="server" Text="+ Produto" OnClick="ButtonAdd_Click" UseSubmitBehavior="false" />
                </FooterTemplate>					
    
    <HeaderStyle CssClass="GridViewHeaderStyle"></HeaderStyle>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Deletar" HeaderStyle-CssClass="GridViewHeaderStyle">
                <ItemTemplate>
                     <asp:Button ID="ButtonDel" runat="server" Text="X" OnClick="ButtonDel_Click" UseSubmitBehavior="false" />
                </ItemTemplate>
              
    <HeaderStyle CssClass="GridViewHeaderStyle"></HeaderStyle>
            </asp:TemplateField>
              <asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
            </Columns>
    </asp:gridview>

    quinta-feira, 30 de janeiro de 2014 17:53