Move grid rows up or down on button click - asp.net

I have a grid that I am trying to move the grid rows either up or down based on button click. Here is what I have so far.
Protected Sub imgBtnMoveUp_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
Dim imgBtn As ImageButton
Dim FirstRow As GridViewRow = gvQuoteSo.Rows(0)
Dim btnUp As Button = DirectCast(FirstRow.FindControl("MoveUp"), Button)
Dim gvrow As GridViewRow
Dim previousRow As GridViewRow
Dim index As Integer = 0
imgBtn = CType(sender, ImageButton)
If imgBtn.CommandName = "MoveUp" Then
index = Convert.ToInt32(imgBtn.CommandArgument)
gvrow = gvQuoteSo.Rows(index)
previousRow = gvQuoteSo.Rows(index - 1)
UpdatePanelGrid.Update()
End If
End Sub
When I click the button for up nothing hapens. I know this is just the move up function but if I can get help with that then the move down will answer itself. Thanks so much!

Explanations are given in comments.
Private Sub btnUp_Click(sender As Object, e As EventArgs)
Dim grid As DataGridView = Grid_view
Try
Dim totalRows As Integer = grid.Rows.Count ' will count the number of rows
Dim idx As Integer = grid.SelectedCells(0).OwningRow.Index ' row index of the selected cell
If idx = 0 Then ' for no rows selected
Return
End If
Dim col As Integer = grid.SelectedCells(0).OwningColumn.Index ' columns corresponding to the selected row
Dim rows As DataGridViewRowCollection = grid.Rows
Dim row As DataGridViewRow = rows(idx)
rows.Remove(row) ' Remove the corrent row
rows.Insert(idx - 1, row)' Re-insert the row
grid.ClearSelection()
grid.Rows(idx - 1).Cells(col).Selected = True
Catch
End Try
End Sub
Private Sub btnDown_Click(sender As Object, e As EventArgs)
Dim grid As DataGridView = Grid_view
Try
Dim totalRows As Integer = grid.Rows.Count
Dim idx As Integer = grid.SelectedCells(0).OwningRow.Index
If idx = totalRows - 2 Then
Return
End If
Dim col As Integer = grid.SelectedCells(0).OwningColumn.Index
Dim rows As DataGridViewRowCollection = grid.Rows
Dim row As DataGridViewRow = rows(idx)
rows.Remove(row)
rows.Insert(idx + 1, row)
grid.ClearSelection()
grid.Rows(idx + 1).Cells(col).Selected = True
Catch
End Try
End Sub

Related

ASP.Net Looping Through Gridview After adding Group Row

In a GridView I am adding Grouping rows to the underlying table in the RowDataBound, but when I ApplyChanges and loop through each GridViewRow not all rows can be tested for TextBox value etc, the number of rows is reduced by the number of grouping rows inserted. Although it does loop through the grouping rows which I ignore, and misses the last n rows.
Private tmpSiteName As String = ""
Private Sub gvVehicles_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvVehicles.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim drv As DataRowView = DirectCast(e.Row.DataItem, DataRowView)
If tmpSiteName <> drv("lcname").ToString() Then
tmpSiteName = drv("lcname").ToString()
Dim tbl As Table = TryCast(e.Row.Parent, Table)
If tbl IsNot Nothing Then
Dim row As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
Dim cell As New TableCell()
' Span the row across all of the columns in the Gridview
cell.ColumnSpan = Me.gvVehicles.Columns.Count
cell.Width = Unit.Percentage(100)
'cell.Style.Add("font-weight", "bold")
cell.Style.Add("background-color", "#f5f5f5")
cell.Style.Add("color", "#000000")
Dim span As New HtmlGenericControl("span")
span.InnerHtml = tmpSiteName
cell.Controls.Add(span)
row.Cells.Add(cell)
tbl.Rows.AddAt(tbl.Rows.Count - 1, row)
End If
End If
End If
End Sub
Private Sub ApplyChanges()
Dim AuctionDB As fleet.AuctionDB = New fleet.AuctionDB
Dim OldFleetNo As String = ""
Dim NewFleetNo As String = ""
Dim OldReserve As Integer = 0
Dim NewReserve As Integer = 0
Dim MTA As Long = 0
Dim Sitekey As String = ""
Dim vcaudit As Long = 0
Dim i As Integer = gvVehicles.Rows.Count
Try
For Each DRow As GridViewRow In gvVehicles.Rows
Sitekey = TryCast(DRow.FindControl("hiddenSitekey"), HiddenField).Value
MTA = Val(TryCast(DRow.FindControl("hiddenMTA"), HiddenField).Value)
strChange = ""
' The Grouping rows throw up funny results, but we can catch MTA = 0
If MTA > 0 Then
OldFleetNo = TryCast(DRow.FindControl("hiddenFleetNo"), HiddenField).Value
NewFleetNo = TryCast(DRow.FindControl("txtFleetNo"), TextBox).Text
If NewFleetNo <> OldFleetNo Then
vcaudit = AuctionDB.FleetUpdates(Sitekey, MTA, "FLEET NO", OldReserve, NewFleetNo, Session("user_name"))
updateCount += 1
strChange = "Fleet No. changed from " & OldFleetNo & " to " & NewFleetNo & "<br /><br />"
End If
End If
Next DRow
Catch ex As Exception
ShowMessage("Error: " & ex.Message, "alert-danger")
End Try
End Sub

Dropdown not firing event on usercontrol

I have a dropdown list which is inside a user control on my page.
When I select an item in a gridview it fills some data including this dropdown list selecting the correspondent value to the gridview row.
Then I can change the selection, but when i try to do that the Selected Index Changed event isn't firing. At least not at first. If i select again it fires.
I'm using asp.net with VB.
I have put AutoPostback = true, I've set the Handles in the codebehind method, I've set a default empty line and set it to default selection, but I can't get it to work.
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Page.IsPostBack() Then
fillProd()
Dim cert As String = Session("var")
isFilled = Session("isFilled")
If Not IsNothing(cert) And Not isFilled Then
FillFields(cert)
End If
End If
End Sub
Private Sub fillProd()
dt = HttpContext.Current.Session("dt")
Dim row() As DataRow = dt.Select()
Dim dtProductos As New DataTable()
dtProductos.Columns.Add(New DataColumn("valorcombo", GetType(String)))
dtProductos.Columns.Add(New DataColumn("textocombo", GetType(String)))
Dim firstrow As DataRow = dtProductos.NewRow()
firstrow (0) = 0
firstrow (1) = ""
dtProductos.Rows.Add(firstrow)
For i As Integer = 0 To row.Length - 1
Dim fila As DataRow = dtProductos.NewRow()
fila(0) = row(i)("cod")
fila(1) = row(i)("text")
dtProductos.Rows.Add(fila)
Next
ddlproductos.DataSource = dtProductos
ddlproductos.DataTextField = "textocombo"
ddlproductos.DataValueField = "valorcombo"
ddlproductos.DataBind()
ddlproductos.SelectedIndex = 0
End Sub
Private Sub FillFields(cert As String)
Dim dtSubsData As DataTable = GetData(cert)
If Not IsNothing(dtSubsData) Then
Dim row As DataRow = dtSubsData.Rows(0)
ddlproductos.ClearSelection()
ddlproductos.SelectedValue = row("cod").ToString()
Session("isFilled") = True
isFilled = Session("isFilled")
End If
End Sub
Can anyone help?

Get all selected values of CheckBoxList in VB.NET

I've used ASP's CheckBoxList control. Now what I want is to get the all selected values in VB code.
HTML
<asp:CheckBoxList ID="chkbxlst_Users" runat="server" RepeatColumns="2" RepeatDirection="Vertical" RepeatLayout="Table"></asp:CheckBoxList>
VB
Protected Sub btnSaveSetProject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveSetProject.Click
Dim ds_selectedProjects As New DataSet
Dim eStr As String = String.Empty
Try
Catch ex As Exception
Me.ShowErrorMessage(ex.Message, "...btnSaveSetProject")
End Try
End Sub
On this Save button's click I want to get all the selected items' value and text in dataset.
try this..
For Each li As ListItem In chkbxlst_Users.Items
If li.Selected Then
// add item data into your dataset
Else
// do whatever you need
End If
End If
Next
You can try following code:
Protected Sub btnSaveSetProject_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSaveSetProject.Click
Dim ds_selectedProjects As New DataSet
Dim dt = New DataTable()
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcName)
Dim eStr As String = String.Empty
Try
For Each checkBox As CheckBox In chkbxlst_Users.Items
If (checkBox.Checked = True) Then
Dim dr As DataRow = dt.NewRow()
dr("ID") = checkBox.Text
dt.Rows.Add(dr)
End If
Next
ds_selectedProjects.Tables.Add(dt)
Catch ex As Exception
'Me.ShowErrorMessage(ex.Message, "...btnSaveSetProject")
End Try
End Sub
Try this code
Dim ds_selectedProjects As New DataSet
Dim dt_selectedProjects As New DataTable
dt_selectedProjects.Columns.Add("Value")
dt_selectedProjects.Columns.Add("Text")
Dim dr As DataRow
For i = 0 To chkbxlst_Users.Items.Count - 1
If chkbxlst_Users.Items(i).Selected Then
dr = dt_selectedProjects.NewRow()
dr("Value") = Val(chkbxlst_Users.Items(i).Value)
dr("Text") = chkbxlst_Users.Items(i).Text
dt_selectedProjects.Rows.Add(dr)
End If
Next
ds_selectedProjects.Tables.Add(dt_selectedProjects)
Try this
Dim str As [String] = ""
For i As Integer = 0 To CheckBoxList1.Items.Count - 1
If CheckBoxList1.Items(i).Selected Then
If str = "" Then
str = "'" + CheckBoxList1.Items(i).Value + "'"
Else
str += "," + "'" + CheckBoxList1.Items(i).Value + "'"
End If
End If
Next
'display in a textbox or lable with ID txtmsg
txtmsg.Text = str

gridview loop issue

I have a gridview with 4 columns, three of them are template fields where the user can enter the information needed and click a button to submit it to the database. I have 2 issues:
When I click my button to add a second row... the data in the first row posts
disappears. I want to be able to add the row without the first row of information
disappearing for multiple record entry situations. My code follows:
Private Sub SetInitialRow()
Dim dts As New DataTable()
Dim drs As DataRow = Nothing
dts.Columns.Add(New DataColumn("Approval Date", GetType(String)))
dts.Columns.Add(New DataColumn("Total Amount", GetType(String)))
dts.Columns.Add(New DataColumn("Comments", GetType(String)))
dts.Columns.Add(New DataColumn("Initials", GetType(String)))
drs = dts.NewRow()
drs("Approval Date") = String.Empty
drs("Total Amount") = String.Empty
drs("Comments") = String.Empty
drs("Initials") = String.Empty
dts.Rows.Add(drs)
ViewState("CurrentTable") = dts
gvOLIAdj.DataSource = dts
gvOLIAdj.DataBind()
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
'extract the TextBox values
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
drCurrentRow = dtCurrentTable.NewRow()
drCurrentRow("Approval Date") = box1.Text
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
'dtCurrentTable.Rows(i - 1)("Initials") =
rowIndex += 1
Next
dtCurrentTable.Rows.Add(drCurrentRow)
ViewState("CurrentTable") = dtCurrentTable
gvOLIAdj.DataSource = dtCurrentTable
gvOLIAdj.DataBind()
End If
Else
Response.Write("ViewState is null")
End If
'Set Previous Data on Postbacks
SetPreviousData()
End Sub
Private Sub SetPreviousData()
Dim rowIndex As Integer = 0
If ViewState("CurrentTable") IsNot Nothing Then
Dim dats As DataTable = DirectCast(ViewState("CurrentTable"), DataTable)
If dats.Rows.Count > 0 Then
For i As Integer = 0 To dats.Rows.Count - 1
Dim box1 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(1).FindControl("txtAdjAppr"), TextBox)
Dim box2 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(2).FindControl("txtAdjAmt"), TextBox)
Dim box3 As TextBox = DirectCast(gvOLIAdj.Rows(rowIndex).Cells(3).FindControl("txtCmmts"), TextBox)
box1.Text = dats.Rows(i)("Approval Date").ToString()
box2.Text = dats.Rows(i)("Total Amount").ToString()
box3.Text = dats.Rows(i)("Comments").ToString()
rowIndex += 1
Next
End If
End If
End Sub
Protected Sub btnAddNewRow_Click(sender As Object, e As EventArgs) Handles btnAddNewRow.Click
AddNewRowToGrid()
End Sub
When I try to write a loop that will loop through each of the template fields to grab
the data and put it into my database it doesn't recognize that I have data in the
template fields? This is what I have tried thus far to no avail...
Protected Sub btn_Update_Click(sender As Object, e As EventArgs) Handles btn_Update.Click
For Each row As GridViewRow In gvOLIAdj.Rows
For Each gv As GridViewRow In gvOLIAdj.Rows
Dim appDt As String = (Rows(rowIndex).Cells(1).FindControl("txtAdjAppr")), TextBox)
Dim approvalDt As String = CType(gv.FindControl("txtAdjAppr"), TextBox).Text
Dim totalAmt As String = CType(gv.FindControl("txtAdjAmt"), TextBox).Text
Dim comments As String = CType(gv.FindControl("txtcmmts"), TextBox).Text
Dim intitials As String = DirectCast(gv.FindControl("total"), TextBox).Text
Next
End Sub
In your AddNewRowToGrid method you are doing the following:
dtCurrentTable.Rows(i - 1)("Total Amount") = box2.Text
dtCurrentTable.Rows(i - 1)("Comments") = box3.Text
What's wrong here is the updating of the row in dtCurrentTable.Rows(i - 1). You are updating the values in the row above that which you wish to update.

Dynamic gridview columns event problem

i have a GridView (selectable) in which I want to generate a dynamic GridView in a new row BELOW the selected row.
I can add the row and gridview dynamically in the Gridview1 PreRender event. I need to use this event because:
_OnDataBound is not called on every postback (same for _OnRowDataBound)
_OnInit is not possible because the 'Inner table' for the Gridview is added after Init
_OnLoad is not possible because the 'selected' row is not selected yet.
I can add the columns to the dynamic GridView based on my ITemplate class.
But now the button events won't fire.... Any suggestions?
The dynamic adding of the gridview:
Private Sub GridView1_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView1.PreRender
Dim g As GridView = sender
g.DataBind()
If g.SelectedRow IsNot Nothing AndAlso g.Controls.Count > 0 Then
Dim t As Table = g.Controls(0)
Dim r As New GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal)
Dim c As New TableCell
Dim visibleColumnCount As Integer = 0
For Each d As DataControlField In g.Columns
If d.Visible Then
visibleColumnCount += 1
End If
Next
c.ColumnSpan = visibleColumnCount
Dim ph As New PlaceHolder
ph.Controls.Add(CreateStockGrid(g.SelectedDataKey.Value))
c.Controls.Add(ph)
r.Cells.Add(c)
t.Rows.AddAt(g.SelectedRow.RowIndex + 2, r)
End If
End Sub
Private Function CreateStockGrid(ByVal PnmAutoKey As String) As GridView
Dim col As Interfaces.esColumnMetadata
Dim coll As New BLL.ViewStmCollection
Dim entity As New BLL.ViewStm
Dim query As BLL.ViewStmQuery = coll.Query
Me._gridStock.AutoGenerateColumns = False
Dim buttonf As New TemplateField()
buttonf.ItemTemplate = New QuantityTemplateField(ListItemType.Item, "", "Button")
buttonf.HeaderTemplate = New QuantityTemplateField(ListItemType.Header, "", "Button")
buttonf.EditItemTemplate = New QuantityTemplateField(ListItemType.EditItem, "", "Button")
Me._gridStock.Columns.Add(buttonf)
For Each col In coll.es.Meta.Columns
Dim headerf As New QuantityTemplateField(ListItemType.Header, col.PropertyName, col.Type.Name)
Dim itemf As New QuantityTemplateField(ListItemType.Item, col.PropertyName, col.Type.Name)
Dim editf As New QuantityTemplateField(ListItemType.EditItem, col.PropertyName, col.Type.Name)
Dim f As New TemplateField()
f.HeaderTemplate = headerf
f.ItemTemplate = itemf
f.EditItemTemplate = editf
Me._gridStock.Columns.Add(f)
Next
query.Where(query.PnmAutoKey.Equal(PnmAutoKey))
coll.LoadAll()
Me._gridStock.ID = "gvChild"
Me._gridStock.DataSource = coll
AddHandler Me._gridStock.RowCommand, AddressOf Me.gv_RowCommand
Me._gridStock.DataBind()
Return Me._gridStock
End Function
The ITemplate class:
Public Class QuantityTemplateField : Implements ITemplate
Private _itemType As ListItemType
Private _fieldName As String
Private _infoType As String
Public Sub New(ByVal ItemType As ListItemType, ByVal FieldName As String, ByVal InfoType As String)
Me._itemType = ItemType
Me._fieldName = FieldName
Me._infoType = InfoType
End Sub
Public Sub InstantiateIn(ByVal container As System.Web.UI.Control) Implements System.Web.UI.ITemplate.InstantiateIn
Select Case Me._itemType
Case ListItemType.Header
Dim l As New Literal
l.Text = "<b>" & Me._fieldName & "</b>"
container.Controls.Add(l)
Case ListItemType.Item
Select Case Me._infoType
Case "Button"
Dim ib As New Button()
Dim eb As New Button()
ib.ID = "InsertButton"
eb.ID = "EditButton"
ib.Text = "Insert"
eb.Text = "Edit"
ib.CommandName = "Edit"
eb.CommandName = "Edit"
AddHandler ib.Click, AddressOf Me.InsertButton_OnClick
AddHandler eb.Click, AddressOf Me.EditButton_OnClick
container.Controls.Add(ib)
container.Controls.Add(eb)
Case Else
Dim l As New Label
l.ID = Me._fieldName
l.Text = ""
AddHandler l.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(l)
End Select
Case ListItemType.EditItem
Select Case Me._infoType
Case "Button"
Dim b As New Button
b.ID = "UpdateButton"
b.Text = "Update"
b.CommandName = "Update"
b.OnClientClick = "return confirm('Sure?')"
container.Controls.Add(b)
Case Else
Dim t As New TextBox
t.ID = Me._fieldName
AddHandler t.DataBinding, AddressOf Me.OnDataBinding
container.Controls.Add(t)
End Select
End Select
End Sub
Private Sub InsertButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("insert click")
End Sub
Private Sub EditButton_OnClick(ByVal sender As Object, ByVal e As EventArgs)
Console.WriteLine("edit click")
End Sub
Private Sub OnDataBinding(ByVal sender As Object, ByVal e As EventArgs)
Dim boundValue As Object = Nothing
Dim ctrl As Control = sender
Dim dataItemContainer As IDataItemContainer = ctrl.NamingContainer
boundValue = DataBinder.Eval(dataItemContainer.DataItem, Me._fieldName)
Select Case Me._itemType
Case ListItemType.Item
Dim fieldLiteral As Label = sender
fieldLiteral.Text = boundValue.ToString()
Case ListItemType.EditItem
Dim fieldTextbox As TextBox = sender
fieldTextbox.Text = boundValue.ToString()
End Select
End Sub
End Class
Oh my oh my, I went to MVC, anybody reading this question should do the same :)

Resources