Insert separator row in Gridview - asp.net

I'm new to ASP.NET VB, and i'm having trouble and dont really understand the code of putting in row seperators in a gridview. I have 5 columns and the fifth columns rows field text is what i would like inserted into the new seperator row. There may be more than one per question. To populate my gridview i'm calling upon a stored procedure "Select_Problems" and carrying a persons name from another page through "SvarRecord" and matching it up with the SP #Name. The fifth column in the SP has four possibilities "1. Person upset?", "2. Is Person is resisting?", and so on. My code is as follows and i would like to have an easy way to do this but to make it look nice along with a color to divide each question. Thank you
Public Sub LoadGrid2()
Dim MyConn As New SqlConnection((ConfigurationManager.ConnectionStrings("Customer_Service").ConnectionString))
Dim MyCmd As New SqlDataAdapter("Select_Problems", MyConn)
MyCmd.SelectCommand.CommandType = CommandType.StoredProcedure
MyCmd.SelectCommand.Parameters.Add(New SqlParameter("#Name", SqlDbType.VarChar))
MyCmd.SelectCommand.Parameters("#Name").Value = Session("SvarRecord")
Dim ds As New DataSet
MyConn.Open()
MyCmd.Fill(ds, "Overview")
GridView2.DataSource = ds
GridView2.DataBind()
End Sub
I know your supposed to do this in the Rowdatabound of the Gridview but I dont understand the code behind it to do this which would be great to do.

In the RowDataBound event, you could check the index of the row currently being bound and determine if it is the last row in a set of 5 and then apply styling to the row to give a visual cue of separation without actually generating a blank separator row, like this:
Protected Sub GridView2_RowDataBound(sender As Object, e As GridViewRowEventArgs)
' Add a visual separator via CSS border property to every 5th row
If e.Row.RowIndex Mod 5 = 0 Then
' Apply style to each cell in the row
For Each cell As TableCell In e.Row.Cells
cell.Attributes.Add("Style", "border-bottom: red 5px solid")
Next
End If
End Sub
Note: My math might be off by one so you may need to change the styling to the top of the row (border-top instead of border-bottom), but the idea is the same.

Related

IsNumeric function extremly slow

Have gridview that I have populate from a database, and now I would like right align all the numeric items in the gridview, but If IsNumeric(row.Cells(i).Text) statment takes extremely long time is there any other way to fix this?
Code:
Takes long time any other way align number to the right
For Each row As GridViewRow In Me.gwResult.Rows
For i As Integer = 0 To headCell - 1
If IsNumeric(row.Cells(i).Text) Then
row.Cells(i).HorizontalAlign = HorizontalAlign.Right
End If
Next
Next
You are using this code to identify the numeric values after binding DataSource, which will add extra time to analyse the grid data. Try using the same code on RowDataBound event of the gridview.
Your best option would be to find out which columns are numeric before you bind the grid to the datasource. In the RowDataBound event of the GridView you can then just check if the current column being databound is in the numericColumns collection or not.
'Find numeric properties of the type beehing databound
Dim numericColumns = New HashSet(GetType(MyDataType).GetProperties() _
.Where(Function(x) IsNumericType(x.PropertyType)))
.Select(Function(x) x.Name))
'And for DataTable it would look like this
Dim numericColumns = New HashSet(dt.Columns.Cast(Of DataColumn)() _
.Where(Function(x) IsNumericType(x.DataType))) _
.Select(Function(x) x.ColumnName))
Private Shared Function IsNumericType(dataType As Type) As Boolean
Dim code = CInt(Type.GetTypeCode(dataType ))
Return code >= 4 AndAlso code <= 15
End Function

Dynamically Adding Multiple User Controls vb.net

I have a User Control which returns a table of data, which in some cases needs to be looped, displaying one on top of another.
I am able to dynamically add a single instance of this by placing a fixed placeholder in the page.
I am now trying to work out how to add more than one, given that I don't know how many might be needed I don't want to hard code the Placeholders.
I've tried the following, but I am just getting one instance, presumably the first is being overwritten by the second
My HTML
<div id="showHere" runt="server"/>
VB
Dim thisPh As New PlaceHolder
thisPh.Controls.Add(showTable)
showHere.Controls.Add(thisPh)
Dim anotherPh As New PlaceHolder
anotherPh .Controls.Add(showTable)
showHere.Controls.Add(anotherPh)
How do I make it add repeated tables within the showHere div?
I would advise generating a different ID for each of your table. For example,
Dim i As Integer
i = 0
For each tbl in ShowTables
tbl.ID = "MyTab" + i.ToString()
i = i + 1
showHere.Controls.Add(tbl)
showHere.Controls.Add(New LiteralControl("<br />"))
Next
On other hand, it would make more sense to have a your user/custom control generate html for a single table and then nest your user/custom control within a repeater (or similar control such as ListView etc).
Did you tried simply, this:
For each tbl in ShowTables
showHere.Controls.Add(tbl)
showHere.Controls.Add(New LiteralControl("<br />"))
Next
After fussing with this issue myself, I stumbled across below solution.
On button click()
LocationDiv.Visible = True
Dim existingItems As New List(Of Object)
If Not Session("existingItems") Is Nothing Then
existingItems = CType(Session("existingItems"), List(Of Object))
For Each item As Object In existingItems
LocationDiv.Controls.Add(item)
Next
existingItems.Clear()
End If
LocationDiv.Controls.Add(New LiteralControl("<b>" & Text & "</b>"))
For Each item As Object In LocationDiv.Controls
existingItems.Add(item)
Next
Session.Add("existingItems", existingItems)

ASP Table doesnt save state

I created an ASP Table Control and added a row to it programatically. I then repeated the process to add another row. The first row that I added disappeared and only the newest row is being displayed. Is there a property that needs to be set to allow the state of the table to be saved?
EDIT:
All I do is click a button on the page and it adds a row to the table. Repeated clicks of the button only add one from to the table. If it helps, here is the function that adds the rows.
Protected Sub addItemButton(sender As Object, e As EventArgs)
'get the id of the item they selected
Dim id As String = CType(sender, Button).Text
'clear out the data being displayed
gridViewItemSearchItems.DataSource = Nothing
gridViewItemSearchItems.DataBind()
'add this item to the line table
Dim itemToAdd As Item = gp.Items.GetItemByKey(id)
Dim tableRow As New System.Web.UI.WebControls.TableRow()
Dim cellId As New System.Web.UI.WebControls.TableCell
cellId.Text = itemToAdd.Key.Id
Dim cellDesc As New System.Web.UI.WebControls.TableCell
cellDesc.Text = itemToAdd.Description
Dim cellMSRP As New System.Web.UI.WebControls.TableCell
cellMSRP.Text = gp.Items.GetItemMSRP(itemToAdd.Key)
Dim cellCost As New System.Web.UI.WebControls.TableCell
cellCost.Text = itemToAdd.CurrentCost.Value
Dim cellUnitPrice As New System.Web.UI.WebControls.TableCell
cellUnitPrice.Text = itemToAdd.StandardCost.Value
Dim cellDiscount As New System.Web.UI.WebControls.TableCell
cellDiscount.Text = "12%"
Dim cellQuantity As New System.Web.UI.WebControls.TableCell
cellQuantity.Text = "1"
tableRow.Cells.Add(cellId)
tableRow.Cells.Add(cellDesc)
tableRow.Cells.Add(cellMSRP)
tableRow.Cells.Add(cellCost)
tableRow.Cells.Add(cellUnitPrice)
tableRow.Cells.Add(cellDiscount)
tableRow.Cells.Add(cellQuantity)
tblItems.Rows.Add(tableRow)
End Sub
Since you're adding the rows to your table dynamically, they have to be re-created on each successive post-back.
Look at this answer for an explanation as to why dynamically added controls can disappear: ASP.NET dynamically created controls and Postback
EDIT: It is possible to dynamically add controls during a post-back, my answer here shows a way to do that using ViewState. Although, this does become very cumbersome. You might want to re-think the design of the page.

Adding hyperlinks dynamically by code

I have a web form but I have to do this by code since I dont know the number of hyperlinks I need from the beginning.
How can I add some hyperlinks with Image in a label, the number of hyperlink depends on the number of rows of a query, and each row give me the link information to navigate.
Thanks in advance.
As you loop through your data you can manually add a link to the row something like this:
For i As Integer = 0 To 10
Dim row As New HtmlTableRow
row.Cells.Add(New HtmlTableCell)
Dim Link As New HyperLink
Link.Text = "WhateverText"
Link.NavigateUrl = "page.aspx"
Link.ImageUrl = "~/Theme/Images/SomeImage.gif"
Link.ToolTip = "ToolTipText"
row.Cells(0).Controls.Add(Link)
Next
That of course adds the link as the first cell in an html table. Not sure how you plan to display your data.
In response to the comment below. You can instead insert the new cell something like this
For i As Integer = 0 To 10
Dim row As New HtmlTableRow
Dim cell As New HtmlTableCell
row.Cells.Insert(1, cell)
Dim Link As New HyperLink
Link.Text = "WhateverText"
Link.NavigateUrl = "page.aspx"
Link.ImageUrl = "~/Theme/Images/SomeImage.gif"
Link.ToolTip = "ToolTipText"
row.Cells(0).Controls.Add(Link)
Next
You could also simply add the control to the existing cell that the label is in instead of making a new cell. You can do that by the index value of your existing cell (starting at 0 for each cell that is in the row)
This question is similar to what you want to do:
Auto increment asp control ID
Two options either use a repeater or dynamically add the controls to a panel or some other container control.

How can I copy object types in VB.NET?

I am building an ASP.NET application that needs dynamic tables. That's another issue that I've already posted about (and gotten a pretty good response!). Now, I'm running into another issue - I want to add new rows to my table, but given that I will have 10-12 tables on one page, each containing different objects in their rows (text boxes, check boxes, etc.) I need a way of simply generically adding a new row that has the same objects as the first row in the table. Here's my code:
Private Sub AddTableRow(ByRef originalTable As System.Web.UI.WebControls.Table)
Dim originalRow As System.Web.UI.WebControls.TableRow = originalTable.Rows(1)
Dim insertingRow As New System.Web.UI.WebControls.TableRow
Dim insertingCells(originalRow.Cells.Count) As System.Web.UI.WebControls.TableCell
Dim index As Integer = 0
For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells
insertingCells(index) = New System.Web.UI.WebControls.TableCell
insertingCells(index).Controls.Add(cell.Controls.Item(0))
index += 1
Next
insertingRow.Cells.AddRange(insertingCells)
originalTable.Rows.Add(insertingRow)
End Sub
But I'm getting a null reference exception at the second to last line,
insertingRow.Cells.AddRange(insertingCells)
...and I can't figure out why. Is it because the contents of each cell are not being initialized with a new object? If so, how would I get around this?
Thanks!
EDIT:
The inside of my for loop now looks like this -
For Each cell As System.Web.UI.WebControls.TableCell In originalRow.Cells
Dim addedContent As New Object
Dim underlyingType As Type = cell.Controls.Item(0).GetType
addedContent = Convert.ChangeType(cell.Controls.Item(0), underlyingType)
insertingCells(index) = New System.Web.UI.WebControls.TableCell
insertingCells(index).Controls.Add(addedContent)
index += 1
Next
Stepping through with a debugger, I see that this strategy is working - but the additional table row still doesn't appear...and still does when I do this statically.
I think your culprit may be this line:
Dim insertingCells(originalRow.Cells.Count) As TableCell
Confusingly, the number you specify in an array declaration in VB.NET is the upper bound, not the number of elements. So Dim ints(10) As Integer will create an Integer() array with eleven elements, not ten (10 will be the highest index of the array).
Try this instead:
Dim insertingCells(originalRow.Cells.Count - 1) As TableCell

Resources