I have done research on how to manually create sorting in a grid-view and none of it is thorough enough for me to follow. I need more of a step by step solution, like what event should my sorting code go in, how would i enable the headers to allow sorting. normally, i just have .net do this but for some reason this time it doesn't allow it, maybe because i am not using a datasource.
that's my code that creates a datable and then binds to the gridview.
Function toptable()
Dim reader As SqlDataReader
cmd.Parameters.AddWithValue("#yeartoget", DropDownList1.SelectedValue)
cmd.Parameters.AddWithValue("#mode", RadioButtonList1.SelectedValue)
If TextBox1.Text = "" Then
Dim d As Date = Date.Today
TextBox1.Text = d.AddDays(-1)
End If
Dim pyear As Date
Dim pyear1 As Date
pyear = TextBox1.Text
Dim year1 As Int16
year1 = (pyear.Year - DropDownList1.SelectedValue)
If pyear.Year <> Now.Year Then
pyear1 = (pyear.AddYears(-(year1 + 1)))
Else
pyear1 = (pyear.AddYears(-year1))
End If
cmd.Parameters.AddWithValue("#current", TextBox1.Text)
cmd.Parameters.AddWithValue("#search", pyear1)
cmd.CommandText = "asoftour"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = conn
cmd.CommandTimeout = 300
conn.Open()
reader = cmd.ExecuteReader()
mytable.clear()
myTable.Load(reader)
conn.Close()
Dim currentppax As New DataColumn
currentppax = New DataColumn("AVGPPAX", GetType(Double))
currentppax.Expression = "IIf([CurrentPAX] = 0, 0, [CurrentSales] / [CurrentPAX])"
Dim selectedppax As New DataColumn
selectedppax = New DataColumn("AVGpPAX1", GetType(Double))
selectedppax.Expression = "IIf([asofPAX] = 0, 0, [asofSales] / [asofPAX])"
Dim projsales As New DataColumn
projsales = New DataColumn("ProjSales", GetType(Double))
projsales.Expression = "IIF([PercentSales] = 0, [CurrentSales], [CurrentSales] / [PercentSales])"
Dim projpax As New DataColumn
projpax = New DataColumn("ProjPAX", GetType(Double))
' projpax.Expression = "IIF([PercentPAX] = 0, [CurrentPAX], [CurrentPAX] / [percentpax] )"
projpax.Expression = "IIF([PercentPAX] = 0, [CurrentPAX], [CurrentPAX] / [percentpax] )"
Dim remainingsales As New DataColumn
remainingsales = New DataColumn("remainingsales", GetType(Double))
remainingsales.Expression = "ProjSales - currentsales"
Dim remainingpax As New DataColumn
remainingpax = New DataColumn("remainingpax", GetType(Double))
remainingpax.Expression = "Projpax - currentpax"
Dim movementpax As New DataColumn
movementpax = New DataColumn("movementPAX", GetType(Double))
movementpax.Expression = "IIF([ASOFPAX] = 0, 2,(CurrentPAX / [ASOFPAX]))-1"
Dim movementsales As New DataColumn
movementsales = New DataColumn("movementsales", GetType(Double))
movementsales.Expression = "IIF([ASOFsales] = 0, 2,(Currentsales / [ASOFsales]))-1"
myTable.Columns.Add(selectedppax)
myTable.Columns.Add(currentppax)
myTable.Columns.Add(projsales)
myTable.Columns.Add(projpax)
myTable.Columns.Add(remainingsales)
myTable.Columns.Add(remainingpax)
myTable.Columns.Add(movementsales)
myTable.Columns.Add(movementpax)
GridView1.DataSource = myTable
GridView1.DataBind()
Dim row As New GridViewRow(0, -1, DataControlRowType.Header, DataControlRowState.Normal)
'spanned cell that will span the columns I don't want to give the additional header
Dim compare As TableCell = New TableHeaderCell()
compare.ColumnSpan = 8
row.Cells.Add(compare)
compare.Text = DropDownList1.Text
'spanned cell that will span the columns i want to give the additional header
Dim current As TableCell = New TableHeaderCell()
current.ColumnSpan = 3
current.Text = Year(Now())
row.Cells.Add(current)
Dim Projection As TableCell = New TableHeaderCell()
Projection.ColumnSpan = 4
Projection.Text = "Projections"
row.Cells.Add(Projection)
Dim Movements As TableCell = New TableHeaderCell()
Movements.ColumnSpan = 2
Movements.Text = "Movement"
row.Cells.Add(Movements)
'Add the new row to the gridview as the master header row
'A table is the only Control (index[0]) in a GridView
DirectCast(GridView1.Controls(0), Table).Rows.AddAt(0, row)
And thats my client side code
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" CellSpacing="2" AutoGenerateColumns="False" ShowFooter="True" Font-Size="Smaller" AllowSorting="True" OnRowDataBound="GridView1_RowDataBound" OnSorting="GridView1_Sorting">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField FooterText="Totals:" HeaderText="Regions">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Tour") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Tour") %>'></asp:Label>
</ItemTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="As Of Sales">
<ItemTemplate>
<%#Getsales(Decimal.Parse(Eval("asofsales").ToString())).ToString("C0")%>
</ItemTemplate>
<FooterTemplate>
<%#Getsales1().ToString("C0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="YE Sales">
<ItemTemplate>
<%#Getyesales(Decimal.Parse(Eval("yesales").ToString())).ToString("C0")%>
</ItemTemplate>
<FooterTemplate>
<%#Getyesales1().ToString("C0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="PCT Sales">
<ItemTemplate>
<%#GetAvesales(Decimal.Parse(Eval("percentSales").ToString())).ToString("P1")%>
</ItemTemplate>
<FooterTemplate>
<%#GetAvesales1().ToString("P1")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="As Of PAX">
<ItemTemplate>
<%#Getpax(Decimal.Parse(Eval("asofpax").ToString())).ToString("N0")%>
</ItemTemplate>
<FooterTemplate>
<%#Getpax1().ToString("N0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="YE PAX">
<ItemTemplate>
<%#Getyepax(Decimal.Parse(Eval("YEpax").ToString())).ToString("N0")%>
</ItemTemplate>
<FooterTemplate>
<%#Getyepax1().ToString("N0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="PCT PAX">
<ItemTemplate>
<%#GetAvepax(Decimal.Parse(Eval("percentpax").ToString())).ToString("P2")%>
</ItemTemplate>
<FooterTemplate>
<%#GetAvepax1().ToString("P1")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="AVG PPAX">
<ItemTemplate>
<%#GetAveppax(Decimal.Parse(Eval("AVGppax1").ToString())).ToString("C0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetpreviousAveppax1().ToString("C0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Current Sales">
<ItemTemplate>
<%#GetCsales(Decimal.Parse(Eval("CurrentSales").ToString())).ToString("C0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetCsales1().ToString("C0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Current PAX">
<ItemTemplate>
<%#GetCpax(Decimal.Parse(Eval("CurrentPAX").ToString())).ToString("N0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetCpax1().ToString("N0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="AVG PPAX">
<ItemTemplate>
<%#GetAveppax(Decimal.Parse(Eval("AVGppax").ToString())).ToString("C0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetAveppax1().ToString("C0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Proj. Sales">
<ItemTemplate>
<%#GetPsales(Decimal.Parse(Eval("ProjSales").ToString())).ToString("C0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetPsales1().ToString("C0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Proj. PAX">
<ItemTemplate>
<%#GetPpax(Decimal.Parse(Eval("ProjPax").ToString())).ToString("N0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetPpax1().ToString("N0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Remaining Sales">
<ItemTemplate>
<%#GetRPsales(Decimal.Parse(Eval("remainingsales").ToString())).ToString("C0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetRPsales1().ToString("C0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Remaining PAX">
<ItemTemplate>
<%#GetRPpax(Decimal.Parse(Eval("RemainingPax").ToString())).ToString("N0")%>
</ItemTemplate>
<FooterTemplate>
<%#GetRPpax1().ToString("N0")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="PCT. Pax">
<ItemTemplate>
<%#Getmovepax(Decimal.Parse(Eval("movementPAX").ToString())).ToString("P1")%>
</ItemTemplate>
<FooterTemplate>
<%#Getmovepax1().ToString("P1")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="PCT. Sales">
<ItemTemplate>
<%#Getmovesales(Decimal.Parse(Eval("movementsales").ToString())).ToString("P1")%>
</ItemTemplate>
<FooterTemplate>
<%#Getmovesales1().ToString("P1")%>
</FooterTemplate>
<FooterStyle Font-Bold="True" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Theme">
<ItemTemplate>
<asp:Label ID="lbltheme" runat="server" Text="Label"></asp:Label><br />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is what i tried but no links show on my headers.
Public Property GridViewSortDirection() As SortDirection
Get
If ViewState("sortDirection") Is Nothing Then
ViewState("sortDirection") = SortDirection.Ascending
End If
Return DirectCast(ViewState("sortDirection"), SortDirection)
End Get
Set(ByVal value As SortDirection)
ViewState("sortDirection") = value
End Set
End Property
Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
Dim sortExpression As String = e.SortExpression
If GridViewSortDirection = SortDirection.Ascending Then
GridViewSortDirection = SortDirection.Descending
SortGridView(sortExpression, SortDirection.Descending)
Else
GridViewSortDirection = SortDirection.Ascending
SortGridView(sortExpression, SortDirection.Ascending)
End If
End Sub
Private Sub SortGridView(ByVal sortExpression As String, ByVal direction As String)
' You can cache the DataTable for improving performance
Dim dv As New DataView(myTable)
dv.Sort = sortExpression & direction
GridView1.DataSource = dv
GridView1.DataBind()
End Sub
You need to set the SortExpression.
You can do it in code behind using something like the following:
Private Sub setSortExpression()
Try
Dim field As DataControlField
For Each field In gridView.Columns
If TypeOf field Is BoundField Then
Dim dbf As BoundFielddbf = DirectCast(field, BoundField)
field.SortExpression = dbf.DataField
End If
Next
Catch ex As Exception
End Try
End Sub
Actually, I figured it out. I had to add the sort expression to the client side code.
To fix my problem the first step, was to add the sort expression, to the client side code.
<asp:TemplateField HeaderText="As Of Sales" SortExpression= "asofsales">
This fixed my problem to allow sorting, but it would only sort in one direction ascending. I had the correct sorting code the problem is I had to add a couple things.
Private Sub SortGridView(ByVal sortExpression As String, ByVal direction As String)
If direction = "1" Then
direction = "ASC"
Else
direction = "DESC"
End If
' You can cache the DataTable for improving performance
transferview.Sort = sortExpression + " " + direction
GridView1.DataSource = transferview
GridView1.DataBind()
End Sub
End Class
Before i was using
transferview.Sort = sortExpression + direction , which would not work because it would concatenate, the two strings together and use them as a column name, which would cause the program not to find the column. So i simply changed it to
transferview.Sort = sortExpression + " " + direction
and it worked perfectly.
Convert the sort order
dv.Sort = sortExpression & " " & ConvertSortDirectionToSql(direction)
Related
Aim: Gridview with checkbox on each line, user then clicks a button and all ticked lines are actioned in the button code. I need the ID's of all the records where the CheckBox is checked.
Error:
Object reference not set to an instance of an object.
on row: ID_Current = row.FindControl("ID").ToString
if I change the to ID_Current = DirectCast(row.FindControl("cbSelect"), CheckBox).Checked I get 'True' as a result but I already know that and want to get the ID.
Aspx-Code with my Gridview:
<asp:Panel ID="ActionGrid" runat="Server">
<h2>Actions To Edit</h2>
<asp:GridView ID="GridView3" runat="server" AllowPaging="True" AllowSorting="True" AlternatingRowStyle-CssClass="alt" AutoGenerateColumns="False" CssClass="mGrid" DataKeyNames="UPRN" DataSourceID="SqlDataSource3" EmptyDataText="There are no data records to display." Font-Size="Medium" PagerStyle-CssClass="pgr" Width="1000px">
<%-- AutoGenerateEditButton="True"--%>
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="cbSelect" runat="server" AutoPostBack="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ControlStyle-Width="50px" DataField="UPRN" HeaderText="UPRN" ReadOnly="True" SortExpression="UPRN" />
<asp:BoundField DataField="LocationItemPosition" HeaderText="Location Item Position" ReadOnly="True" SortExpression="LocationItemPosition" />
<asp:TemplateField HeaderText="Surveye" SortExpression="SurveyDate">
<ItemTemplate>
<asp:Label ID="lblSurveyDate" runat="server" Text='<%# apFunctionCharacters.fncDateTidy(Eval("SurveyDate"))%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ItemRef" HeaderText="Item Ref" ReadOnly="True" SortExpression="ItemRef" />
<asp:BoundField DataField="OverallRiskCategory" HeaderText="Overall Risk Category" ReadOnly="True" SortExpression="OverallRiskCategory" />
<asp:BoundField DataField="Comments" HeaderText="Comments" ReadOnly="True" SortExpression="Comments" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
</asp:GridView>
<asp:Button ID="btnChangeToNA" runat="server" CssClass="Button" Text="Change to NA" />
<asp:Label ID="lblTest" runat="server" Text="Label"></asp:Label>
</asp:Panel>
Submit button:
<asp:Button ID="btnChangeToNA" runat="server" CssClass="Button" Text="Change to NA" />
.aspx.vb stored procedure/action code
Protected Sub btnChangeToNA_Click(sender As Object, e As EventArgs) Handles btnChangeToNA.Click
For Each row As GridViewRow In GridView3.Rows
Dim ID_Current As String = ""
'read the label
If DirectCast(row.FindControl("cbSelect"), CheckBox).Checked Then
ID_Current = row.FindControl("ID").ToString
' change value
'############stored procedure here
Dim connection As SqlConnection
Dim command As New SqlCommand
Dim ds As New DataSet
Dim ConnectionString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("MY_SQL").ToString()
connection = New SqlConnection(ConnectionString1)
connection.Open()
With command
.Connection = connection
.CommandText = "spChangeValue "
.CommandType = CommandType.StoredProcedure
.Parameters.Clear()
.Parameters.AddWithValue("#ID_Current", ID_Current)
.ExecuteNonQuery()
End With
'#############################
lblTest.Text += ID_Current
End If
'Loop
Next
End Sub
With FindControl you find controls(what suprise) not strings. And you have to pass the ID of the control not a property like Id.
So this doesnt make much sense:
Dim ID_Current As String = row.FindControl("ID").ToString()
Instead you could store the ID in a HiddenField, so on aspx:
<asp:HiddenField ID="HiddenID" runat="server" Value='<%# Eval("ID_Current") %>' />
Now you can get the reference to this HiddenField with FindControl:
Dim hiddenID As HiddenField = DirectCast(row.FindControl("HiddenID"), HiddenField)
Dim ID_Current As String = hiddenID.Value
You need a control with the id "ID"
<ItemTemplate>
<asp:HiddenField ID="ID" runat="server" Value='<%# FillMeSomehow%>' />
<asp:CheckBox ID="cbSelect" runat="server" AutoPostBack="false" />
</ItemTemplate>
I'm having a problem with my dropdown lists in my child gridview displaying values. For whatever reason the first dropdown in the row works fine and displays the values from the database, the other ones don't display anything.
Below is the code for my gridviews:
<asp:GridView ID="GVAccounts" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="Horizontal"
style="position: relative; margin-top: 10px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="branch" HeaderText="Branch"
SortExpression="branch" />
<asp:BoundField DataField="no" HeaderText="Account"
SortExpression="account" />
<asp:TemplateField HeaderText="Name" SortExpression="name">
<EditItemTemplate>
<asp:TextBox ID="TextName" runat="server" Text='<%# Eval("name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelName" runat="server" Text='<%# Eval("name") + " " + Eval("surname") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="type" HeaderText="Type" SortExpression="type" />
<asp:BoundField DataField="sub" HeaderText="Sub" SortExpression="sub" />
<asp:BoundField DataField="TotalAmount" HeaderText="Hold"
SortExpression="TotalAmount" />
<asp:BoundField DataField="loc" HeaderText="LOC" DataFormatString="{0:C}" SortExpression="loc" />
<asp:BoundField DataField="locstatus" HeaderText="LOC status"
SortExpression="locstatus" />
<asp:BoundField DataField="HoldCalc" HeaderText="OD/EX Amt" SortExpression="HoldCalc" />
<asp:BoundField DataField="odtimes" HeaderText="#OD" SortExpression="odtimes" />
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="gridChild" style="display: inline; position: relative; left: 15px; overflow: auto">
<asp:GridView ID="gvChildGrid" runat="server" AutoGenerateColumns="false"
BorderStyle="Double" BorderColor="#5D7B9D" Width="80%">
<HeaderStyle BackColor="#5D7B9D" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="#E1E1E1" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true"
oncheckedchanged="chkSelect_CheckedChanged" EnableViewState="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="effective" HeaderText="Effective"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="desc_" HeaderText="Desc"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="code" HeaderText="TC"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="amount" HeaderText="Amount"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="tracer" HeaderText="Cheq #"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="empl" HeaderText="Empl"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:BoundField DataField="balance" HeaderText="OD/EXT Amt"
HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Note">
<ItemTemplate>
<asp:DropDownList ID="DropDownNote" runat="server"
onselectedindexchanged="DropDownNote_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem></asp:ListItem>
<asp:ListItem>MWC</asp:ListItem>
<asp:ListItem>CBM</asp:ListItem>
<asp:ListItem>Return</asp:ListItem>
<asp:ListItem>TSF</asp:ListItem>
<asp:ListItem>OK NO S/C</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Note1">
<ItemTemplate>
<asp:DropDownList ID="ddNote2" runat="server"
onselectedindexchanged="ddNote2_SelectedIndexChanged" AutoPostBack="true">
<asp:ListItem Selected="True">NSF</asp:ListItem>
<asp:ListItem>Funds Not Clear</asp:ListItem>
<asp:ListItem>Post Dated</asp:ListItem>
<asp:ListItem>Stale Dated</asp:ListItem>
<asp:ListItem>Stop Payment</asp:ListItem>
<asp:ListItem>Encoding Incorrect</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Branch">
<ItemTemplate>
<asp:DropDownList ID="ddBranch" runat="server" DataSourceID="BranchDataSource"
DataTextField="branch" DataValueField="branch" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="BranchDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ThirdPartyDataConnectionString %>"
SelectCommand="SELECT [branch] FROM [branch]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Account">
<ItemTemplate>
<asp:TextBox ID="TextNo" runat="server" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Type">
<ItemTemplate>
<asp:DropDownList ID="ddType" runat="server" DataSourceID="typeSource"
DataTextField="Type" DataValueField="Type" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="typeSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ThirdPartyDataConnectionString %>"
SelectCommand="SELECT [Type] FROM [DMDType]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub">
<ItemTemplate><asp:TextBox ID="TextSub" Width="25px" runat="server"></asp:TextBox></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" CssClass="GVFixedHeader" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
Below is the method that is having the issue with displaying:
Private Function CheckForSubmit() As Boolean
Try
conn = New SqlConnection(connectionString)
Dim cmdNote As New SqlCommand("select note, note1, noteBranch, noteAccountNo, noteType, noteSub, id from DmdOD where id = #id order by effective, time_, seqno_dmddmhi_dmhi", conn)
cmd = New SqlCommand("select submitted, id, effective FROM DmdOD where no = #no and entered = '" & ddDate.SelectedItem.Text & "' order by effective, time_, seqno_dmddmhi_dmhi", conn)
Dim objDBId As Object = 0
Dim id = 0
Dim objDate As Date
Dim dateStr As String = ""
If ddDate.SelectedIndex <> -1 Then
cmd = New SqlCommand("select submitted, id, entered FROM DmdOD where no = #no and entered = '" & ddDate.SelectedItem.Text & "' order by effective, time_, seqno_dmddmhi_dmhi", conn)
' cmd.Parameters.Add(New SqlParameter("effective", ddDate.SelectedItem.Text))
Else
cmd = New SqlCommand("select submitted, id, entered FROM DmdOD where no = #no order by effective, time_, seqno_dmddmhi_dmhi", conn)
End If
cmd.CommandType = CommandType.Text
Dim i = 0
For Each row As GridViewRow In GVAccounts.Rows
cmd.Parameters.Add(New SqlParameter("#no", row.Cells(1).Text))
Dim gv As GridView = DirectCast(row.FindControl("gvChildGrid"), GridView)
conn.Open()
Dim idReader As SqlClient.SqlDataReader = cmd.ExecuteReader()
'get ids in order
While (idReader.Read())
If Not objId.Contains(idReader.GetValue(1)) Then
objId.Add(idReader.GetValue(1))
End If
End While
conn.Close()
conn.Open()
Dim reader As SqlClient.SqlDataReader = cmd.ExecuteReader()
While (reader.Read())
objSubmit = reader.GetValue(0)
objDBId = reader.GetValue(1)
objDate = reader.GetValue(2)
dateStr = objDate.ToShortDateString
If dateStr = ddDate.SelectedItem.Text Then
Exit While
End If
End While
conn.Close()
If objSubmit = True And dateStr = ddDate.SelectedItem.Text Then
For Each r As GridViewRow In gv.Rows
cmdNote.Parameters.Add(New SqlParameter("#id", objId(i)))
Dim ddNote As Control = r.FindControl("DropDownNote")
Dim ddl As DropDownList = DirectCast(ddNote, DropDownList)
Dim ddNote2 As Control = r.FindControl("ddNote2")
Dim ddlNote As DropDownList = DirectCast(ddNote2, DropDownList)
ddlNote.Items.Insert(0, New ListItem(String.Empty, String.Empty))
Dim ddBranch As Control = r.FindControl("ddBranch")
Dim ddBranchBox As DropDownList = DirectCast(ddBranch, DropDownList)
ddBranchBox.Items.Insert(0, New ListItem(String.Empty, String.Empty))
Dim txtAccount As Control = r.FindControl("TextNo")
Dim txtAccountBox As TextBox = DirectCast(txtAccount, TextBox)
Dim ddType As Control = r.FindControl("ddType")
Dim ddTypeBox As DropDownList = DirectCast(ddType, DropDownList)
Dim txtSub As Control = r.FindControl("TextSub")
Dim txtSubBox As TextBox = DirectCast(txtSub, TextBox)
r.Cells(0).Enabled = False
r.Cells(8).Enabled = False
r.Cells(9).Enabled = False
r.Cells(10).Enabled = False
r.Cells(11).Enabled = False
r.Cells(12).Enabled = False
r.Cells(13).Enabled = False
'Display fields
gv.Columns(8).Visible = True
gv.Columns(9).Visible = True
gv.Columns(10).Visible = True
gv.Columns(11).Visible = True
gv.Columns(12).Visible = True
gv.Columns(13).Visible = True
ddBranchBox.Visible = True
txtAccount.Visible = True
ddTypeBox.Visible = True
txtSub.Visible = True
'Get Data for fields
conn.Open()
cmdNote.ExecuteNonQuery()
Dim readNotes As SqlClient.SqlDataReader = cmdNote.ExecuteReader()
readNotes.Read()
'Note
If IsDBNull(readNotes.GetValue(0)) Then
ddl.SelectedItem.Text = ""
Else
ddl.SelectedItem.Text = readNotes.GetValue(0)
End If
'Note1
If IsDBNull(readNotes.GetValue(1)) Then
'GVAccounts.Columns(12).Visible = False
ddlNote.Visible = False
ddlNote.SelectedItem.Text = ""
Else
'ddlNote.SelectedItem.Text = readNotes.GetValue(1)
ddlNote.SelectedItem.Selected = False
ddlNote.Items.FindByText(readNotes.GetValue(1)).Selected = True
End If
'Branch
If IsDBNull(readNotes.GetValue(2)) Then
ddBranchBox.Visible = False
ddBranchBox.SelectedItem.Text = ""
Else
ddBranchBox.SelectedItem.Text = readNotes.GetValue(2)
End If
'Account
If IsDBNull(readNotes.GetValue(3)) Then
txtAccountBox.Visible = False
txtAccountBox.Text = ""
Else
txtAccountBox.Text = readNotes.GetValue(3)
End If
'Type
If IsDBNull(readNotes.GetValue(4)) Then
ddTypeBox.Visible = False
ddTypeBox.SelectedItem.Text = ""
Else
ddTypeBox.SelectedItem.Text = readNotes.GetValue(4)
End If
'Sub
If IsDBNull(readNotes.GetValue(5)) Then
txtSubBox.Visible = False
txtSubBox.Text = ""
Else
txtSubBox.Text = readNotes.GetValue(5)
End If
conn.Close()
i += 1
cmdNote.Parameters.Clear()
Next
ButtonSubmit.Enabled = False
ButtonSave.Enabled = False
ButtonSaveTop.Enabled = False
End If
i = 0
'cmd.Parameters.Clear()
'cmdNote.Parameters.Clear()
objSubmit = False
dateStr = ""
cmd.Parameters.RemoveAt(0)
cmdNote.Parameters.Clear()
objId.Clear()
Next
If objSubmit = True Then
Return objSubmit
End If
Catch ex As Exception
LblErr.ForeColor = Drawing.Color.DarkRed
LblErr.Text = "CheckForSubmit - " & ex.Message
Finally
conn.Dispose()
End Try
Return Nothing
End Function
Edit: I should also note that when I step through the code I see that the dropdowns do in fact have values, yet nothing is being displayed for them on the gridview, I'm stumped.
Updated answer
I would compare drop down lists "note" and "note1"
e.g. note works but note1 doesn't.
The difference I can see between the 2 is that note has an empty list item. Try adding an empty list item to note 1.
Failing that, copy the working code from note and gradually replace it with the values from Note1, checking if/when it fails.
I am trying to export selected columns from GridView to Excel, and every time I run the code an error pops up with some new .dll file name. What could be the issue? Please find the code below for your reference.
<asp:Panel ID="general" runat="server" BorderColor="#333333" BorderStyle="Double" CssClass="emailpnl" Width="800px">
<asp:GridView ID="bestpractgrv" runat="server" AutoGenerateColumns="False" OnLoad="bestpractgrv_Load" CellPadding="3" GridLines="Vertical" Width="100%" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" AllowPaging="True" OnPageIndexChanging = "OnPaging">
<AlternatingRowStyle BackColor="Gainsboro" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkboxSelectAll" runat="server" onclick="CheckAllEmp(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID ="boolcb" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="idlbl" runat="server" Text='<%# Bind("iID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Discipline ID">
<ItemTemplate>
<asp:Label ID="discplnlbl" runat="server" Text='<%# Bind("iDisciplineID")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Created">
<ItemTemplate>
<asp:Label ID="dateclbl" runat="server" Text='<%# Bind("dDateCreated")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Title">
<ItemTemplate>
<asp:Label ID="bptitlelbl" runat="server" Text='<%# Bind("cBPTitle")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</asp:Panel>
VB Code
Private Sub PopulateCheckBoxArray()
Dim CheckBoxArray As ArrayList
If ViewState("CheckBoxArray") IsNot Nothing Then
CheckBoxArray = DirectCast(ViewState("CheckBoxArray"), ArrayList)
Else
CheckBoxArray = New ArrayList()
End If
Dim CheckBoxIndex As Integer
Dim CheckAllWasChecked As Boolean = False
Dim chkAll As CheckBox = DirectCast(bestpractgrv.HeaderRow.Cells(0).FindControl("chkboxSelectAll"), CheckBox)
Dim checkAllIndex As String = "chkboxSelectAll-" & bestpractgrv.PageIndex
If chkAll.Checked Then
If CheckBoxArray.IndexOf(checkAllIndex) = -1 Then
CheckBoxArray.Add(checkAllIndex)
End If
Else
If CheckBoxArray.IndexOf(checkAllIndex) <> -1 Then
CheckBoxArray.Remove(checkAllIndex)
CheckAllWasChecked = True
End If
End If
For i As Integer = 0 To bestpractgrv.Rows.Count - 1
If bestpractgrv.Rows(i).RowType = DataControlRowType.DataRow Then
Dim chk As CheckBox = DirectCast(bestpractgrv.Rows(i).Cells(0).FindControl("boolcb"), CheckBox)
CheckBoxIndex = bestpractgrv.PageSize * bestpractgrv.PageIndex + (i + 1)
If chk.Checked Then
If CheckBoxArray.IndexOf(CheckBoxIndex) = -1 AndAlso Not CheckAllWasChecked Then
CheckBoxArray.Add(CheckBoxIndex)
End If
Else
If CheckBoxArray.IndexOf(CheckBoxIndex) <> -1 OrElse CheckAllWasChecked Then
CheckBoxArray.Remove(CheckBoxIndex)
End If
End If
End If
Next
ViewState("CheckBoxArray") = CheckBoxArray
End Sub
And I get the error on following line
Dim chkAll As CheckBox = DirectCast(bestpractgrv.HeaderRow.Cells(0).FindControl("chkboxSelectAll"), CheckBox)
This is the error message
An exception of type 'System.NullReferenceException' occurred in App_Web_pqx0e3wy.dll but was not handled in user code
After every compilation the dll name changes, while App_Web_XXXX.dll remains constant
I know this question has been asked several times before and I have tried many of the suggested solutions. I am attempting to bold each row of my GridView that contains the text "Earned" or "Total" (haven't added "total" code yet). I have successfully gotten the DataBound event to fire, and I've successfully gotten it to recognize the 2 For looping statements that I use to loop through each row and column (I use labels to let me know which code blocks I've accessed and the counts are 24 rows and 9 columns), but for some reason, the code that I use to specifically determine if the cell contains the text "Earned" won't fire. I'm not sure what I'm doing wrong. Could someone take a look and help me understand what I'm doing wrong? Thank you for your help!
Here's my ASP code for the GridView (sorry, not sure why it's in multiple blocks):
<asp:GridView ID="gv_VacationDetails" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataSourceID="VacationDetails_DataSource" GridLines="Vertical" style="z-index: 1; left: 24px; top: 275px; position: absolute; height: 220px; width: 435px" ShowFooter="True" EnableViewState="True" AutoPostback="True" OnRowDataBound="gv_VacationDetails_DataBound">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Action" SortExpression="Employee_Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Employee_Name") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="ddl_InsertVacAction" runat="server" OnSelectedIndexChanged="gv_VacationDetails_SelectedIndexChanged" EnableViewState="True" AutoPostback="True" TabIndex="1">
<asp:ListItem>Adjustments</asp:ListItem>
<asp:ListItem>Used</asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Employee_Name") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="False" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Middle" Wrap="False" />
</asp:TemplateField>
<asp:BoundField DataField="Unit_Area_ID" HeaderText="Unit_Area_ID" SortExpression="Unit_Area_ID" Visible="False" />
<asp:TemplateField HeaderText="Vacation (Days)" SortExpression="Vacation" FooterStyle-Width="133px" FooterStyle-Wrap="false">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Vacation")%'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txb_InsertVacHours" runat="server" Width="115px" TabIndex="2"></asp:TextBox>
<asp:RequiredFieldValidator ID="val_VacationTimeReq" runat="server" ControlToValidate="txb_InsertVacHours" ErrorMessage="Vacation Time is a required field. Please enter in DAYS." ForeColor="#FF3300" ValidationGroup="Vacation">*</asp:RequiredFieldValidator>
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Vacation Time - You can only enter a positive or negative number." ForeColor="Red" Operator="DataTypeCheck" Type="Double" ControlToValidate="txb_InsertVacHours" ValidationGroup="Vacation">*</asp:CompareValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Vacation") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="False" />
<ItemStyle HorizontalAlign="Center" Wrap="False" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Used" SortExpression="Used_Date" FooterStyle-Wrap="false">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("Used_Date") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="tbx_InsertVacUsed" runat="server" Width="115px" TabIndex="3"></asp:TextBox>
<asp:RegularExpressionValidator ID="Val_VacDateCheck" runat="server" ControlToValidate="tbx_InsertVacUsed" ErrorMessage="Vacation Used - Please enter the dat in format mm/dd/yyyy" ForeColor="#FF3300" ValidationExpression="^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$" ValidationGroup="Vacation">*</asp:RegularExpressionValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Used_Date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="False" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Updated" SortExpression="Update_Date">
<EditItemTemplate>
<asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Update_Date") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btn_InsertVacation" runat="server" CommandName="InsertVacation" Text="Add Action" TabIndex="4" />
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Bind("Update_Date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="False" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Wrap="False" />
</asp:TemplateField>
<asp:BoundField DataField="First_Name" HeaderText="First_Name" SortExpression="First_Name" Visible="False" />
<asp:BoundField DataField="Last_Name" HeaderText="Last_Name" SortExpression="Last_Name" Visible="False" />
<asp:BoundField DataField="Unit_ID" HeaderText="Unit_ID" SortExpression="Unit_ID" Visible="False" />
<asp:BoundField DataField="HireRehire" HeaderText="HireRehire" SortExpression="HireRehire" Visible="False" />
<asp:BoundField DataField="Display_Year" HeaderText="Display_Year" SortExpression="Display_Year" Visible="False" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
Here is my DataBound code:
Public Sub gv_VacationDetails_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Label6.Text = "Inside Bold"
'Label6.Text = gv_VacationDetails.Rows(1).Cells("Action").Text.ToString
Dim r As Integer
Dim c As Integer
For r = 0 To gv_VacationDetails.Rows.Count - 1
Label6.Text = "Inside ROW"
For c = 0 To gv_VacationDetails.Columns.Count - 1
Label6.Text = "Inside COLUMN"
Label7.Text = "Rows = " & CType(gv_VacationDetails.Rows.Count - 1, String) & "; Columns = " & CType(gv_VacationDetails.Columns.Count - 1, String)
If gv_VacationDetails.Rows(r).Cells(c).Text.Trim = "Earned" Then
Label6.Text = "Inside BOLD IF"
gv_VacationDetails.Rows(r).Cells(c).Font.Bold = True
'gv_VacationDetails.Rows(r).Cells(c).ForeColor = Drawing.Color.Red
End If
Next
Next
'For i = 1 To gv_VacationDetails.Rows.Count - 1
' 'Label6.Text = gv_VacationDetails.Rows(i).Cells(1).Text.ToString
' If gv_VacationDetails.Rows(i).Cells(0).Text = "Earned" Then
' Label6.Text = "Inside Bold IF"
' gv_VacationDetails.Rows(i).Font.Bold = True
' End If
'Next
'If e.Row.RowType = DataControlRowType.DataRow Then
' Label6.Text = "Inside Bold IF"
' Dim drv As DataRowView = CType(e.Row.DataItem, DataRowView)
' If CType(drv(0), String) = "Earned" Or CType(drv(0), String) = "Total Adjustments" Or _
' CType(drv(0), String) = "Total Used" Or CType(drv(0), String) = "Total Remaining" Then
' e.Row.Font.Bold = True
' End If
'End If
End Sub
The method you used to access the GridView rows cells will only work with bound fields not template fields. In order to access a template field you can use Row.FindControl method.
Please try this instead in your gv_VacationDetails_DataBound method:
Public Sub gv_VacationDetails_DataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
'First you need to get the template fields, which are labels as in GridView your design
Dim Label1 As Label = DirectCast(e.Row.FindControl("Label1"), Label)
Dim Label2 As Label = DirectCast(e.Row.FindControl("Label2"), Label)
Dim Label3 As Label = DirectCast(e.Row.FindControl("Label3"), Label)
Dim Label4 As Label = DirectCast(e.Row.FindControl("Label4"), Label)
'Next you can check each field value
If Label1.Text = "Earned" Then
Label1.Font.Bold = True
End If
If Label2.Text = "Earned" Then
Label2.Font.Bold = True
End If
If Label3.Text = "Earned" Then
Label3.Font.Bold = True
End If
If Label4.Text = "Earned" Then
'Label6.Text = "Inside BOLD IF"
Label4.Font.Bold = True
End If
'You can check the bound fields by looping through row cells
For Each cell As TableCell In e.Row.Cells
If cell.Text = "Earned" Then
cell.Font.Bold = True
End If
Next
End If
End Sub
I have checked all available articles and none seem to help me.
I have a GridView that is located inside a Repeater control. The data that populates the Gridview is dynamic and is grouped by a SectionID. I need for each repeated GridView to list the data rows grouped according to their SectionID.
How do I do this?
Thanks.
Here is what I have so far:
Public Sub GrabRepeaterData()
Dim connstr As String = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim ss As New SqlConnection(connstr)
Dim sqlStr As String = "SELECT SectionID, Name FROM Table1"
Dim selectCMD As New SqlClient.SqlCommand(sqlStr, ss)
Dim dt As New DataTable
Dim ds As New DataSet
Dim dataAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
dataAdapter.SelectCommand = selectCMD
dataAdapter.Fill(dt)
selectCMD.Dispose()
dataAdapter.Dispose()
ss.Close()
ss.Dispose()
dt.Columns.Add("Column1")
dt.Columns.Add("Column2")
dt.Columns.Add("Column3")
dt.Columns.Add("Column4")
dt.Columns.Add("Column5")
dt.Columns.Add("Column6")
dt.Columns.Add("Column7")
dt.Columns.Add("Column8")
For Each row As DataRow In dt.Rows
Dim SectionID As String = ""
SectionID = row("SectionID")
Dim Column1 As String = ""
Dim Column2 As String = ""
Dim Column3 As Boolean
Dim Column4 As String = ""
Dim Column5 As String = ""
Dim Column6 As String = ""
Dim Column7 As Boolean
Dim Column8 As Boolean
Dim ProgConn As String = ""
ProgConn = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim ProgSqlQuery As New SqlConnection(ProgConn)
Dim ProgResults As New SqlCommand("SELECT [Column1], [Column2], [Column3], [Column4], [Column5], [Column6], [Column7], [Column8] FROM Table2 WHERE SectionID = #SectionID ORDER BY Column4 DESC", ProgSqlQuery)
ProgResults.Parameters.AddWithValue("#SectionID", SectionID).Value = SectionID
ProgSqlQuery.Open()
Dim rProg As SqlDataReader = ProgResults.ExecuteReader()
While rProg.Read()
If Not rProg("Column1").Equals(DBNull.Value) Then
Column1 = CStr(rProg("Column1"))
End If
If Not rProg("Column2").Equals(DBNull.Value) Then
Column2 = CStr(rProg("Column2"))
End If
If Not rProg("Column3").Equals(DBNull.Value) Then
Column3 = CStr(rProg("Column3"))
End If
If Not rProg("Column4").Equals(DBNull.Value) Then
Column4 = CStr(rProg("Column4"))
End If
If Not rProg("Column5").Equals(DBNull.Value) Then
Column5 = CStr(rProg("Column5"))
End If
If Not rProg("Column6").Equals(DBNull.Value) Then
Column6 = CStr(rProg("Column6"))
End If
If Not rProg("Column7").Equals(DBNull.Value) Then
Column7 = CStr(rProg("Column7"))
End If
If Not rProg("Column8").Equals(DBNull.Value) Then
Column8 = CStr(rProg("Column8"))
End If
End While
rProg.Close()
ProgResults.Dispose()
ProgSqlQuery.Close()
ProgSqlQuery.Dispose()
row("Column1") = Column1
row("Column2") = Column2
row("Column3") = Column3
row("Column4") = Column4
row("Column5") = Column5
row("Column6") = Column6
row("Column7") = Column7
row("Column8") = Column8
row.EndEdit()
dt.AcceptChanges()
Next
CustomInfoRepeater.DataSource = dt
CustomInfoRepeater.DataBind()
End Sub
Protected Sub CustomInfoRepeater_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles CustomInfoRepeater.ItemDataBound
If e.Item.ItemType = ListItemType.Item Then
Try
Dim grdVw As GridView = TryCast(e.Item.FindControl("CustomInfoGridView"), GridView)
grdVw.DataSource = DirectCast(e.Item.DataItem, DataTable).Rows
grdVw.DataBind()
Dim CustPanel As UpdatePanel = DirectCast(CustomInfoRepeater.Items(0).FindControl("CustomInfoPanel"), UpdatePanel)
CustPanel.Update()
Catch
End Try
End If
End Sub
Here is my HTML:
<asp:Repeater ID="CustomInfoRepeater" runat="server">
<ItemTemplate>
<div class="download-box3">
</h2>
<asp:UpdatePanel ID="CustomInfoPanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:PostBackTrigger ControlID="CustomInfoGridView" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="CustomInfoGridView" runat="server" Width="100%" AutoGenerateColumns="False"
DataKeyNames="Column1" GridLines="None" RowStyle-Height="40px" EnableViewState="False"
CellPadding="4" ForeColor="#333333" RowStyle-VerticalAlign="Middle">
<Columns>
<asp:BoundField DataField="Column1" />
<asp:TemplateField ItemStyle-Width="35px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:ImageButton ID="newIcon" runat="server" Width="31px" CssClass="myGridImage"
Visible="false" ImageUrl="images/new.png" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="35px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="30px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:ImageButton ID="DeleteButton" runat="server" AlternateText="Delete" ImageUrl="images/xmark.png"
OnClientClick="return confirm('Are you sure you want to delete this entry?')"
CommandArgument='<%# Eval("Column1") %>' CommandName="Remove" CssClass="myGridImage">
</asp:ImageButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="30px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="50px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:LinkButton ID="GenComUpdateButton" runat="server" CssClass="buttonsmall" Text="update"
CommandArgument='<%# Eval("Column1") %>' CommandName="GenComments"></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Impact" HeaderStyle-HorizontalAlign="Center" ItemStyle-Width="30px"
ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Image ID="statusIcon" runat="server" Width="20px" CssClass="myGridImage" Visible="false"
ImageUrl="" AlternateText="*" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="50px" HeaderText="Files" ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:ImageButton ID="filesIcon" runat="server" Width="23px" CssClass="myGridImage"
CommandArgument='<%# Eval("Column3") %>' CommandName="Download" Visible="false"
ImageUrl="images/pdf.png" AlternateText="*" />
<asp:LinkButton ID="AttachAssetsBtn" runat="server" CssClass="buttonredsmall" Text="upload"
CommandArgument='<%# Eval("Column1") %>' CommandName="Uploads" Visible="false"></asp:LinkButton>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:BoundField DataField="Column3" HeaderText="Summary" HeaderStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle">
<HeaderStyle HorizontalAlign="Center"></HeaderStyle>
<ItemStyle VerticalAlign="Middle" HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField ItemStyle-Width="50px" HeaderText="Reviewed" ItemStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle">
<ItemTemplate>
<asp:Image ID="reviewedIcon" runat="server" Width="23px" CssClass="myGridImage" Visible="false"
ImageUrl="images/checkmark.png" AlternateText="*" />
<asp:CheckBox ID="reviewedCheckBox" runat="server" CssClass="inputtext" Visible="false"
AutoPostBack="true" OnCheckedChanged="GenComCheckUpdate" />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
</asp:TemplateField>
<asp:BoundField DataField="Column4" HeaderText="Updated" HeaderStyle-HorizontalAlign="Center"
ItemStyle-VerticalAlign="Middle" ItemStyle-Width="75px">
<ItemStyle VerticalAlign="Middle" HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="Column6" Visible="false" />
<asp:BoundField DataField="Column7" Visible="false" />
</Columns>
<EmptyDataTemplate>
<span class="data-none">No Comments have been added to this section.</span>
</EmptyDataTemplate>
<RowStyle CssClass="RowStyle" BackColor="#F7F6F3" ForeColor="#333333" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
<PagerStyle CssClass="PagerStyle" BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle CssClass="SelectedRowStyle" BackColor="#E2DED6" Font-Bold="True"
ForeColor="#333333" />
<HeaderStyle CssClass="HeaderStyle" BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle CssClass="EditRowStyle" BackColor="#999999" />
<AlternatingRowStyle CssClass="AltRowStyle" BackColor="White" ForeColor="#284775" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</ItemTemplate>
<SeparatorTemplate>
<hr />
</SeparatorTemplate>
</asp:Repeater>
Thanks for your help!
What I understand from the code is you are merging two datasources into one. Then binding it to the Repeater and then fetching the datasource for GV from the repeater DataItem and binding it to the GridView.
What I would suggest is keep the datasources separate and do it in two steps:
1: Bind the repeater to just the SectionID i.e. data returned by SELECT SectionID, Name FROM Table1
2: In the Repeater ItemDataBound, get the SectionID and fetch data with the query you have in ProgResults. Then bind that to the GV.
I totally agree with gbs. Here's how you can do it:
In the markup, add a hidden field inside repeater, outside the updatepanel:
<asp:Repeater ID="CustomInfoRepeater" runat="server">
<ItemTemplate>
<asp:HiddenField ID="hdnSectionID" Value='<%# Eval("SectionID")%>' runat="server" />
<asp:Label ID="lblName" Text='<%# Eval("Name")%>' runat="server"></asp:Label>
<div class="download-box3">
</h2>
<asp:UpdatePanel ID="CustomInfoPanel" runat="server" UpdateMode="Conditional">
<%-- Rest of the markup goes here --%>
Rewrite GrabRepeaterData() sub only to populate the repeater:
Public Sub GrabRepeaterData()
Dim connstr As String = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim dt As New DataTable
Using conn As SqlConnection = New SqlConnection(connstr)
conn.Open()
Dim sqlStr As String = "SELECT SectionID, Name FROM Table1"
Dim cmd As New SqlClient.SqlCommand(sqlStr, conn)
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dt)
End Using
CustomInfoRepeater.DataSource = dt
CustomInfoRepeater.DataBind()
End Sub
In repeater's ItemDataBound, find the HiddenField, find it's value, find the GridView inside UpdatePanel, populate it this way:
Protected Sub CustomInfoRepeater_ItemDataBound(sender As Object, e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles CustomInfoRepeater.ItemDataBound
If e.Item.ItemType = ListItemType.Item Then
Dim sectionID As Integer = 0
Dim hdnSectionID = TryCast(e.Item.FindControl("hdnSectionID"), HiddenField)
Dim CustomInfoPanel = TryCast(e.Item.FindControl("CustomInfoPanel"), UpdatePanel)
If (CustomInfoPanel IsNot Nothing AndAlso hdnSectionID IsNot Nothing AndAlso Integer.TryParse(hdnSectionID.Value, sectionID)) Then
Dim CustomInfoGridView = TryCast(CustomInfoPanel.FindControl("CustomInfoGridView"), GridView)
If (CustomInfoGridView IsNot Nothing) Then
Dim connstr As String = ConfigurationManager.ConnectionStrings("MyString").ToString()
Dim dt As New DataTable
Using conn As SqlConnection = New SqlConnection(connstr)
conn.Open()
Dim cmd As New SqlCommand("SELECT [Column1], [Column2], [Column3], [Column4], [Column5], [Column6], [Column7], [Column8] FROM Table2 WHERE SectionID = #SectionID ORDER BY Column4 DESC", conn)
cmd.Parameters.AddWithValue("#SectionID", sectionID)
Dim adapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter
adapter.SelectCommand = cmd
adapter.Fill(dt)
End Using
CustomInfoGridView.DataSource = dt
CustomInfoGridView.DataBind()
End If
End If
End If
End Sub