Gridview datacontrolrowtype not recognized as datarow - asp.net

I am trying to learn how to put totals on my gridview and have been searching for 2 days to find why mine don't work. The onrowdatabound event fires, but it doesn't recognize the rows as datarows, it only picks up the footer (I added a textbox and put the value in to make sure I wasn't losing it). I am very new to this and am probably doing something wrong that is very simple.
my codebehind is
Protected Sub WeeklyGridView_RowDataBound(ByVal sender As Object, _
ByVal e As GridViewRowEventArgs) Handles WeeklyGridView.OnRowDataBound
Dim appleTotal As Integer = 0
Dim orangeTotal As Integer = 0
Dim bananaTotal As Integer = 0
Dim pearTotal As Integer = 0
Dim grapeTotal As Integer = 0
Dim peachTotal As Integer = 0
Dim cherryTotal As Integer = 0
Dim pineTotal As Integer = 0
Dim totalTotal As Integer = 0
Dim ThedataType As String
ThedataType = e.Row.RowType.ToString
TextBox1.Text = ThedataType 'this always shows Footer
If e.Row.RowType = DataControlRowType.DataRow Then 'this never fires
appleTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Apple"))
orangeTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Orange"))
bananaTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Banana"))
pearTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Pear"))
grapeTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Grape"))
peachTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Peach"))
cherryTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Cherry"))
pineTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, _
"Pine"))
totalTotal += Convert.ToInt64(DataBinder.Eval(e.Row.DataItem, _
"TOTAL"))
ElseIf e.Row.RowType = DataControlRowType.Footer Then 'this always fires
e.Row.Cells(0).Text = "Totals:"
' for the Footer, display the running totals
e.Row.Cells(3).Text = appleTotal.ToString("g")
e.Row.Cells(4).Text = orangeTotal.ToString("g")
e.Row.Cells(5).Text = bananaTotal.ToString("g")
e.Row.Cells(6).Text = pearTotal.ToString("g")
e.Row.Cells(7).Text = grapeTotal.ToString("g")
e.Row.Cells(8).Text = peachTotal.ToString("g")
e.Row.Cells(9).Text = cherryTotal.ToString("g")
e.Row.Cells(10).Text = pineTotal.ToString("g")
e.Row.Cells(11).Text = totalTotal.ToString("g")
e.Row.Font.Bold = True
End If
End Sub
The gridview is updated based on criteria selected by the user and is made visible and populated when they click on a search button.
The ridiculous code for the search button is: (and I know it's terrible but I'm trying)
Protected Sub SearchButton_Click(sender As Object, e As ImageClickEventArgs) Handles SearchButton.Click
Dim wherecls As String = "trees in ("
Dim whereFNcls As String = "fruitNumber between ("
Dim whereString As String = ""
Dim i As Integer = 0
Dim selectQry As String = "SELECT cast(trees as varchar(3)) as Trees, MIN(fruitnumber) AS FN_Start, MAX(fruitnumber) AS FN_End, COUNT(CASE WHEN fruitType = 'apple' THEN 1 ELSE NULL END) AS apple, COUNT(CASE WHEN fruitType = 'orange' THEN 1 ELSE NULL END) AS orange, COUNT(CASE WHEN fruitType = 'banana' THEN 1 ELSE NULL END) AS banana, COUNT(CASE WHEN fruitType = 'pear' THEN 1 ELSE NULL END) AS pear, COUNT(CASE WHEN fruitType = 'grape' THEN 1 ELSE NULL END) AS grape, COUNT(CASE WHEN fruitType = 'peach' THEN 1 ELSE NULL END) AS peach, COUNT(CASE WHEN fruitType = 'cherry' THEN 1 ELSE NULL END) AS cherry, COUNT(CASE WHEN fruitType = 'pine' THEN 1 ELSE NULL END) AS pine, COUNT(CASE when dcosg is not null THEN 1 ELSE NULL END) AS Total FROM fruitReport WHERE (orchard = #orchard) and "
orchardTextBox.Text = orchardDropDown.SelectedValue
' check if items selected in both listboxes
If trees_Listbox.Items.Count > 0 Then
If fruitminListBox.Items.Count > 0 Then
'cycle through items in fruitnum listbox to create an "in" clause for sql query
For Each item As ListItem In trees_Listbox.Items
whereString += String.Join(",", item) + ", "
Next
whereString = Left(whereString, Len(whereString) - 2) + ")"
selectQry += "(" + wherecls + whereString + ")"
whereFNcls = "(fruitNumber between "
For Each itemFNmin As ListItem In fruitminListBox.Items
'create a "between" clause for the min and max FN values entered by user.
whereOEcls += itemFNmin.Value + " and " + fruitmaxListBox.Items(i).ToString + ") or (fruitNumber between " '(fruitnumber between number and number) or
i += 1
Next
'trim off the last text portion of the whereOEcls
whereOEcls = Left(whereOEcls, Len(whereFNcls) - 25)
selectQry += " and (" + whereFNcls + ") GROUP BY trees ORDER BY trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
Else
'see if FN is empty but trees is selected
For Each item As ListItem In trees_Listbox.Items
whereString += String.Join(",", item) + ", "
Next
whereString = Left(whereString, Len(whereString) - 2)
selectQry += wherecls + whereString + ") GROUP BY trees ORDER BY trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
End If
Else
If fruitminListBox.Items.Count > 0 Then
'check if trees is empty but FN is selected
whereFNcls = "(fruitNumber between "
For Each itemFNmin As ListItem In fruitminListBox.Items
'create a "between" clause for the min and max FN values entered by user.
whereFNcls += itemFNmin.Value + " and " + fruitmaxListBox.Items(i).ToString + ") or (fruitNumber between " '(fruitnumber between number and number) or
i += 1
Next
whereFNcls = Left(whereFNcls, Len(whereFNcls) - 26)
selectQry += whereFNcls + ") GROUP BY trees ORDER BY trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
Else
'if both are empty search only on orchard
selectQry = Left(selectQry, Len(selectQry) - 5) + " group by trees order by trees"
fruityData.SelectCommand = selectQry
WeeklyGridView.Visible = True
End If
End If
End Sub
And lastly, my gridview is...
<asp:GridView ID="WeeklyGridView" runat="server" HorizontalAlign="Center" DataSourceID="fruityData" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Vertical" Visible="False" ShowFooter="True" ShowHeaderWhenEmpty="True">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="trees" HeaderText="trees" SortExpression="trees" />
<asp:BoundField DataField="FN_Start" HeaderText="FN_Start" SortExpression="FN_Start" ReadOnly="True" />
<asp:BoundField DataField="FN_End" HeaderText="FN_End" SortExpression="FN_End" ReadOnly="True" />
<asp:BoundField DataField="apple" HeaderText="apple" SortExpression="apple" ReadOnly="True" />
<asp:BoundField DataField="orange" HeaderText="orange" SortExpression="orange" ReadOnly="True" />
<asp:BoundField DataField="banana" HeaderText="banana" SortExpression="banana" ReadOnly="True" />
<asp:BoundField DataField="pear" HeaderText="pear" SortExpression="pear" ReadOnly="True" />
<asp:BoundField DataField="grape" HeaderText="grape" SortExpression="grape" ReadOnly="True" />
<asp:BoundField DataField="peach" HeaderText="peach" SortExpression="peach" ReadOnly="True" />
<asp:BoundField DataField="cherry" HeaderText="cherry" SortExpression="cherry" ReadOnly="True" />
<asp:BoundField DataField="pine" HeaderText="pine" SortExpression="pine" ReadOnly="True" />
<asp:BoundField DataField="TOTAL" HeaderText="TOTAL" SortExpression="TOTAL" ReadOnly="True" />
</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>
<asp:SqlDataSource ID="fruityData" runat="server" ConnectionString="<%$ ConnectionStrings:fruityStuff %>" >
<SelectParameters>
<asp:ControlParameter ControlID="orchardTextBox" DefaultValue="theGrove" Name="orchard" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Any and all help would be greatly appreciated.

You don't call WeeklyGridView.DataBind() after you've assigned the SqlDataSource.SelectCommand. Try this:
fruityData.SelectCommand = selectQry
fruityData.DataBind()

I knew it was something stupid. I defined the variables inside of the event handler. I should have done it like this.
Dim appleTotal As Integer = 0
Dim orangeTotal As Integer = 0
Dim bananaTotal As Integer = 0
Dim pearTotal As Integer = 0
Dim grapeTotal As Integer = 0
Dim peachTotal As Integer = 0
Dim cherryTotal As Integer = 0
Dim pineTotal As Integer = 0
Protected Sub WeeklyGridView_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles WeeklyGridView.OnRowDataBound

Related

VB.Net Web Application how to add a column below a column on a GridView

How do i add one column under another column so when i make a query output i have two output values in the same row? In my case i want to display Emp ID and under that column i want to display Cust ID so the GridView table can look like this
Emp ID, Rgst ID, Line #, Disc CD, Auth Emp ID, Orig Prc, Disc Amt, Disc Pct, GL Acc ID
Cust ID
Another Question is how can i add a column or header at the end of the "Orig Prc" output as Total and sum all of the "Orig Prc" to Total so it can output the result in the same column as "Orig Prc"? So it can look like this:
ORIG PRC
orig prc output
TOTAL
output is sum of all orig prc output
Can this be done with current method or do i have change my approach on how i output the data on the ViewGrid?
This is my current code:
Protected Sub ExecuteButton_Click(sender As Object, e As EventArgs) Handles ExecuteButton.Click
Dim StoreID As Integer
Dim TransID As Integer
Dim RgstID As Integer
Dim dt As DataTable
If Not Integer.TryParse(StoreIDTextbox.Text, StoreID) Then
MsgBox("Invalid input. Please enter both Store ID and Transaction ID.")
Exit Sub
End If
If Not Integer.TryParse(TransactionIDTextbox.Text, TransID) Then
MsgBox("Invalid input. Please enter both Store ID and Transaction ID.")
Exit Sub
End If
Sql.AddParam("#Str_ID", StoreID)
Sql.AddParam("#Tran_ID", TransID)
'Rgst_ID Validation
If RegisterIDTextbox.Text.Length = 0 Then
SQL.AddParam("#Rgst_ID", "")
ElseIf RegisterIDTextbox.Text.Length > 0 Then
RgstID = Integer.Parse(RegisterIDTextbox.Text)
Sql.AddParam("#Rgst_ID", RgstID)
End If
Try
dt = SQL.ExecQuery("Select H.Emp_ID, H.Cust_ID, H.Rgst_ID, D.TRAN_LN_NUM, D.DISC_CD, D.AUTH_EMP_ID, D.ORIG_PRC, D.DISC_AMT, D.DISC_PCT, D.GL_ACCT_ID
From Transaction_Header H
INNER Join LN_Detail L On (H.Str_ID = L.Str_ID And H.Rgst_ID = L.Rgst_ID And H.Tran_ID = L.Tran_ID)
INNER Join LN_Discount D ON (L.Str_ID = D.Str_ID And L.Rgst_ID = D.Rgst_ID And L.Tran_ID = D.Tran_ID And L.Tran_LN_Num = D.Tran_LN_Num)
WHERE(H.Str_ID = #Str_ID)
And (H.Tran_ID = #Tran_ID)
And ((H.Rgst_ID = #Rgst_ID) Or (#Rgst_ID Is NULL Or #Rgst_ID = ''))")
Catch ex As Exception
MsgBox(ex.Message)
Exit Sub
End Try
GridView2.DataSource = dt
GridView2.DataBind()
TimeLabel.Text = DateAndTime.Now
GridView
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns ="False" CellPadding="4" ForeColor="#333333">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Emp_ID" HeaderText="Emp ID" />
<asp:BoundField DataField="Cust_ID" HeaderText="Cust ID" />
<asp:BoundField DataField="Rgst_ID" HeaderText="Rgst ID" />
<asp:BoundField DataField="TRAN_LN_NUM" HeaderText="Line #" />
<asp:BoundField DataField="DISC_CD" HeaderText="Disc CD" />
<asp:BoundField DataField="AUTH_EMP_ID" HeaderText="Auth Emp ID" />
<asp:BoundField DataField="ORIG_PRC" HeaderText="Orig Prc" />
<asp:BoundField DataField="Disc_Amt" HeaderText="Disc Amt" />
<asp:BoundField DataField="Disc_Pct" HeaderText="Disc Pct" />
<asp:BoundField DataField="GL_ACCT_ID" HeaderText="GL Acct ID" />
</Columns>
In your GridView markup use TemplateColumns instead, this will give you the flexibility you need, e.g.
<asp:TemplateColumn>
<HeaderTemplate>
<b> Tax </b>
</HeaderTemplate>
<ItemTemplate>
<asp:Label
Text='<%# DataBinder.Eval(Container.DataItem, "Tax") %>'
runat="server"/>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox
Text="Taxable"
runat="server"/>
</EditItemTemplate>
<FooterTemplate>
<asp:HyperLink id="HyperLink1"
Text="Microsoft"
NavigateUrl="http://www.microsoft.com"
runat="server"/>
</FooterTemplate>
</asp:TemplateColumn>
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.templatecolumn?view=netframework-4.8

ASP.NET Gridview Paging Issue

I am having issues with the databind method of the gridview control I could use some help on. Some background... I have a search interface with a variety of textboxes (First Name, Last Name, Year, Gender etc.) The user will enter some data and press the search button. At which time I am dynamically generating the SQL for the datasource and binding it to the gridview control.
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
' Check Program Year
If ddYear.SelectedValue = 0 Then
lblStatus.Text = "Please select a program year!"
Exit Sub
Else
lblStatus.Text = ""
End If
ds1.SelectCommand = "SELECT [StudentId], [ProgramYear], [LastName], [Middle], [FirstName], [HighSchoolCode], [Sex], [DateOfBirth] FROM [Student] WHERE [ProgramYear] = " & ddYear.SelectedValue & ""
Dim useCase As Integer = 0
If tbFname.Text <> "" Then useCase = 1
If tbLname.Text <> "" Then useCase = 2
If tbFname.Text <> "" And tbLname.Text <> "" Then useCase = 3
If tbFname.Text <> "" And tbM.Text <> "" Then useCase = 4
If tbID.Text <> "" Then useCase = 5
If tbHSCode.Text <> "" Then useCase = 6
If tbLname.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 7
If tbHSCode.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 8
Select Case useCase
Case 1 'First Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%')"
Case 2 'Last Name
ds1.SelectCommand += " and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 3 'First and Last Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 4 'First and Middle
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([Middle] = '" & tbM.Text & "')"
Case 5 'Student ID
ds1.SelectCommand += " and ([StudentId] = '" & tbID.Text & "')"
Case 6 'HS Code
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "')"
Case 7 'Last Name and Sex
ds1.SelectCommand += " and ([Sex] = '" & ddGender.SelectedValue & "' and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%'))"
Case 8 'HS Code and Sex
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "' and [Sex] = '" & ddGender.SelectedValue & "')"
Case Else
ds1.SelectCommand += " order by [LastName] desc"
End Select
ds1.DataBind()
GridView1.DataBind()
End Sub
This works well however when I enable paging and apply the OnPageIndexChanging method as below I run into trouble.
Protected Sub gridview1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
gridview1.PageIndex = e.NewPageIndex
GridView1.DataSource = ds1
gridview1.databind()
End Sub
What happens is that I click on the paging footer of the gridview to change pages and the gridview does not apply the new binding until I press the submit button again. I am not sure why this is happening any advice is appreciated.
Gridview:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False" DataKeyNames="StudentId" DataSourceID="ds1" AllowPaging="True" PageSize="15">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>.
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Id" InsertVisible="False" SortExpression="StudentId">
<ItemTemplate>
<a href="searchDetail.aspx?StudentID=<%# eval("StudentId") %>" >
<asp:Label ID="xyz" runat="server" Text='<%# Bind("StudentId") %>' /></a>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="Middle" HeaderText="Middle" SortExpression="Middle" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="Sex" HeaderText="Sex" SortExpression="Sex" />
<asp:BoundField DataField="HighSchoolCode" HeaderText="HS Code" SortExpression="HighSchoolCode" />
<asp:BoundField DataField="ProgramYear" HeaderText="Program Year" SortExpression="ProgramYear" />
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
DS1
<asp:SqlDataSource ID="ds1" runat="server" ConnectionString="<%$ ConnectionStrings:NMERITEXString %>"></asp:SqlDataSource>
What you need to do in gridview1_PageIndexChanging is setting gridview1.PageIndex and do the same thing as in btnSubmit_Click.
To avoid code repetition, move the content of btnSubmit_Click to a separate sub, let's call it LoadGrid
Private Sub LoadGrid()
' Check Program Year
If ddYear.SelectedValue = 0 Then
lblStatus.Text = "Please select a program year!"
Exit Sub
Else
lblStatus.Text = ""
End If
ds1.SelectCommand = "SELECT [StudentId], [ProgramYear], [LastName], [Middle], [FirstName], [HighSchoolCode], [Sex], [DateOfBirth] FROM [Student] WHERE [ProgramYear] = " & ddYear.SelectedValue & ""
Dim useCase As Integer = 0
If tbFname.Text <> "" Then useCase = 1
If tbLname.Text <> "" Then useCase = 2
If tbFname.Text <> "" And tbLname.Text <> "" Then useCase = 3
If tbFname.Text <> "" And tbM.Text <> "" Then useCase = 4
If tbID.Text <> "" Then useCase = 5
If tbHSCode.Text <> "" Then useCase = 6
If tbLname.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 7
If tbHSCode.Text <> "" And ddGender.SelectedValue <> "0" Then useCase = 8
Select Case useCase
Case 1 'First Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%')"
Case 2 'Last Name
ds1.SelectCommand += " and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 3 'First and Last Name
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%')"
Case 4 'First and Middle
ds1.SelectCommand += " and ([FirstName] LIKE '%' + '" & tbFname.Text & "' + '%') and ([Middle] = '" & tbM.Text & "')"
Case 5 'Student ID
ds1.SelectCommand += " and ([StudentId] = '" & tbID.Text & "')"
Case 6 'HS Code
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "')"
Case 7 'Last Name and Sex
ds1.SelectCommand += " and ([Sex] = '" & ddGender.SelectedValue & "' and ([LastName] LIKE '%' + '" & tbLname.Text & "' + '%'))"
Case 8 'HS Code and Sex
ds1.SelectCommand += " and ([HighSchoolCode] = '" & tbHSCode.Text & "' and [Sex] = '" & ddGender.SelectedValue & "')"
Case Else
ds1.SelectCommand += " order by [LastName] desc"
End Select
ds1.DataBind()
GridView1.DataSource = ds1;
GridView1.DataBind()
End Sub
then call LoadGrid() inside btnSubmit_Click
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
'set to first page
gridview1.PageIndex = 0
LoadGrid()
End Sub
and also call LoadGrid() in gridview1_PageIndexChanging. Don't forget to add Handles gridview1.PageIndexChanging
Protected Sub gridview1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles gridview1.PageIndexChanging
gridview1.PageIndex = e.NewPageIndex
LoadGrid()
End Sub
Ok I have it working now...
I had to add the loadgrid() sub to the page load as follows. Thanks for your assistance!
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
LoadGrid()
End If
End Sub

Gridview Hypelink values based on row value and column header identifier

I have a gridview in vb.net wich provides a performance value of a list of business names for the previuous week, current week and next week as follows:
LOB W-1 W W+1
--------------------
AMEX 10 15 30
PPR 11 12 14
REM 12 11 10
What I need is for this values to be a hyperlink that opens another window based on the business name and the week to provide further detail. For example, if you want further datail of the value 15 for AMEX and the current week (W) then by pressing the value 15 a new window will open with information for AMEX for the current week.
I have the gridview created but I can not figure out how to do the hyperlinks. Any ideas?
See below code.
<asp:DropDownList ID="DateSelection" runat="server" Height="21px" Width="134px" >
</asp:DropDownList>
<asp:Button ID="Button_Update" runat="server" Text="UPDATE" />
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
GridLines="None" ForeColor="#333333">
<Columns>
<asp:BoundField DataField="LOB" HeaderText="LOB" />
<asp:BoundField DataField="W-1" HeaderText="W-1" />
<asp:BoundField DataField="W" HeaderText="W" />
<asp:BoundField DataField="W+1" HeaderText="W+1" />
</Columns>
</asp:GridView>
vb code
Dim dv_Groups As New System.Data.DataView
Dim dt_Groups As New System.Data.DataTable
dv_Groups = Group.Select(DataSourceSelectArguments.Empty)
dt_Groups = dv_Groups.ToTable()
Dim dv_Main As New System.Data.DataView
Dim dt_Main As New System.Data.DataTable
dv_Main = SQL_Main.Select(DataSourceSelectArguments.Empty)
dt_Main = dv_Main.ToTable()
Dim dt_Report As New DataTable()
dt_Report.Columns.Add("LOB", Type.GetType("System.String"))
dt_Report.Columns.Add("W-1", Type.GetType("System.String"))
dt_Report.Columns.Add("W", Type.GetType("System.String"))
dt_Report.Columns.Add("W+1", Type.GetType("System.String"))
Dim FindRow() As DataRow
Dim SearchText As String
Dim DateS As Date
Dim DateWeek As String
DateS = DateSelection.SelectedItem.Text
Dateweek = Format(DatePart(DateInterval.WeekOfYear, DateS))
For i As Integer = 0 To dt_Groups.Rows.Count - 1
dt_Report.Rows.Add()
dt_Report.Rows(i)(0) = dt_Groups.Rows(i)(0)
SearchText = "LOB like '" & Trim(dt_Report.Rows(i)(0)) & "%' And DateWeek = '" & Dateweek - 1 & "' "
FindRow = dt_Main.Select(SearchText)
dt_Report.Rows(i)(1) = FindRow(0).Item("A_SVL").ToString
SearchText = "LOB like '" & Trim(dt_Report.Rows(i)(0)) & "%' And DateWeek = '" & Dateweek & "' "
FindRow = dt_Main.Select(SearchText)
dt_Report.Rows(i)(2) = FindRow(0).Item("A_SVL").ToString
SearchText = "LOB like '" & Trim(dt_Report.Rows(i)(0)) & "%' And DateWeek = '" & Dateweek + 1 & "' "
FindRow = dt_Main.Select(SearchText)
dt_Report.Rows(i)(3) = FindRow(0).Item("S_SVL").ToString
Next
GridView1.DataSource = dt_Report
GridView1.DataBind()
Many Thanks
You can use a HyperLinkField or TemplateField to add links to your gridview, as shown here:
https://stackoverflow.com/a/8859655/849182

OnSelectedIndexChanged not working first selection, but will on subsequent selections

I have a listbox in a datagrid that is supposed to update upon selection change, and it does, but not on first try. only after it has posted back, after the first time it is clicked will it work as intended. any help appreciated.
Here is the front end portion of the datagrid with the listbox.
<asp:TemplateColumn HeaderText="Qty">
<ItemStyle HorizontalAlign="Center" Wrap="False" CssClass="grid" />
<HeaderStyle HorizontalAlign="Center" ForeColor="Black" Font-Bold="true" CssClass="grid" width="30" />
<ItemTemplate>
<asp:ListBox ID="lstQty" rows="1" runat="server" AutoPostBack="True" EnableViewState="True" OnSelectedIndexChanged="lstQtyUpdate" />
</ItemTemplate>
</asp:TemplateColumn>
Here is the page load section:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
If Not IsPostBack Then
LoadCart()
cartList.Columns(0).Visible = False
If (cartList.Items.Count = 0) Then
cartList.Visible = False
lblEmptyMsg.Visible = True
Else
cartList.Visible = True
lblEmptyMsg.Visible = False
End If
End If
Catch ex As Exception
Errorlog(ex, "Cart.Page_Load()")
End Try
End Sub
This is the sub that is called with the onselectedindexchanged:
Protected Sub lstQtyUpdate(sender As Object, e As System.EventArgs)
Dim lb As New ListBox
lb = CType(sender, ListBox)
Dim thisID As String = lb.ClientID
Dim oiQty As Integer = ComFunctions.ConvertToInt(lb.SelectedItem.Value)
Dim oiID As Integer = 0
For Each item As DataGridItem In cartList.Items
lb = CType(item.FindControl("lstQty"), ListBox)
If (thisID = lb.ClientID) Then
oiID = ComFunctions.ConvertToInt(item.Cells(0).Text)
Exit For
End If
Next.....
Here is the binding for the datagrid, which may be the culprit.
Private Sub cartList_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles cartList.ItemDataBound
Try
Dim rbd As ImageButton
Dim lst As ListBox
Dim id As Integer = 0
Dim evTitle As String = String.Empty
Dim evImage As String = String.Empty
Dim capacity As Integer = 0
Dim soldseats As Integer = 0
Dim seatsleft As Integer = 0
Dim evdate As String = String.Empty
Dim evtimestart As String = String.Empty
Dim evtimeend As String = String.Empty
Dim EditLink As String = String.Empty
Dim DeletedLink As String = String.Empty
If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
id = DataBinder.Eval(e.Item.DataItem, "oi_id")
evTitle = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "title"))
evImage = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "image"))
evdate = ComFunctions.ConvertToDate(DataBinder.Eval(e.Item.DataItem, "eventsdatestart"))
capacity = ComFunctions.ConvertToStr(DataBinder.Eval(e.Item.DataItem, "capacity"))
seatsleft = (capacity - soldseats)
evtimestart = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdatestart")))
evtimeend = ComFunctions.Format_Time((DataBinder.Eval(e.Item.DataItem, "eventsdateend")))
Dim obj_DATA_Capacity As New DATA_Events()
soldseats = obj_DATA_Capacity.GetSeatsSold(id)
e.Item.Cells(0).Text = id
e.Item.Cells(1).Text = evTitle & "<br />" & evdate & " " & evtimestart & " - " & evtimeend
e.Item.Cells(2).Text = "<img src=""" & AppSettings("Events_ImagePath") & "/Thumb/" & evImage & """ width=""100"" />"
e.Item.Cells(3).Text = "$" & ComFunctions.ConvertToDecimal(DataBinder.Eval(e.Item.DataItem, "oi_price"), 2)
lst = CType(e.Item.FindControl("lstQty"), ListBox)
If seatsleft > 0 Then
'lst.Items.Add(0)
For I = 1 To seatsleft
lst.Items.Add(I)
Next
End If
lst.ID = id
lst.SelectedValue = ComFunctions.ConvertToInt(DataBinder.Eval(e.Item.DataItem, "oi_qty"))
rbd = CType(e.Item.FindControl("DeleteThis"), ImageButton)
rbd.CommandArgument = id
End If
Catch ex As Exception
Errorlog(ex, "quickCart.cartList_ItemDataBound()")
End Try
End Sub
I'm not sure why it does not work the first time, by the way, what does "not work" actually mean? But apart from that, your way to get the text of the first cell in the current DataGridItem is odd.
This is much more directly:
Dim lb = DirectCast(sender, ListBox)
Dim item = DirectCast(lb.NamingContainer, DataGridItem)
Dim oiID = Int32.Parse(item.Cells(0).Text)
Maybe it helps also get it working.

ASP.net Dropdowlist added in runtime - event handler not getting fired

THis event does not get fired - not sure why
Protected Sub ddl_selectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim a As String = ""
'this does not get fired
End Sub
<asp:GridView ID="GridViewAssignment" runat="server" BackColor="White" BorderColor="White"
BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None"
Width="100%">
<RowStyle BackColor="#DEDFDE" ForeColor="Black" />
<FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
<PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#86A4CA" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#808080" Font-Bold="True" ForeColor="#E7E7FF" />
</asp:GridView>
Protected Sub GridViewAssignment_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridViewAssignment.RowDataBound
Dim dateApplicationCreatedCell As TableCell = e.Row.Cells(0) 'app created on
Dim typeOfReview As TableCell = e.Row.Cells(7) 'type
Dim QCCell As TableCell = e.Row.Cells(8) 'qc
Dim dateReviewAssignedCell As TableCell = e.Row.Cells(9) 'date assigned
Dim reviewerNameCell As TableCell = e.Row.Cells(10) 'reviewer
Dim dateReviewCompletedCell As TableCell = e.Row.Cells(11) 'date completed review
Dim ddl As DropDownList
If e.Row.RowIndex <> -1 Then
If dateReviewAssignedCell.Text.Trim = " " Then
dateReviewAssignedCell.Text = Now.Date
End If
Dim sqlCondition As String = String.Empty
If dateReviewCompletedCell.Text.Trim = " " Then
Dim nameToSelect As String
If reviewerNameCell.Text.Trim <> " " Then
Dim dateReviewAssigned As Date = dateReviewAssignedCell.Text
Dim elapsedSinceAssigned As Long = DateDiff(DateInterval.Day, dateReviewAssigned.Date, Now.Date, Microsoft.VisualBasic.FirstDayOfWeek.Monday, FirstWeekOfYear.Jan1)
If elapsedSinceAssigned <= 3 Then
dateReviewAssignedCell.BackColor = Drawing.Color.LightGreen
ElseIf elapsedSinceAssigned > 3 And elapsedSinceAssigned <= 5 Then
dateReviewAssignedCell.BackColor = Drawing.Color.Yellow
ElseIf elapsedSinceAssigned > 5 Then
dateReviewAssignedCell.BackColor = Drawing.Color.OrangeRed
End If
nameToSelect = reviewerNameCell.Text.Trim
Else
nameToSelect = String.Empty
End If
If QCCell.Text.ToLower.Contains("qc") Then
If typeOfReview.Text.ToLower.Contains("bca") Then
sqlCondition = "where [QCRole_Level1] = 1 and [BCA] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("ehp") Then
sqlCondition = "where [QCRole_Level1] = 1 and [EHP] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("eligibility") Then
sqlCondition = "where [QCRole_Level1] = 1 and [ProgramEligibility] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("engineering") Then
sqlCondition = "where [QCRole_Level1] = 1 and [Engineering] = 1"
End If
ElseIf QCCell.Text.ToLower.Contains("initial") Then
If typeOfReview.Text.ToLower.Contains("bca") Then
sqlCondition = "where [BCA] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("ehp") Then
sqlCondition = "where [EHP] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("eligibility") Then
sqlCondition = "where [ProgramEligibility] = 1"
ElseIf typeOfReview.Text.ToLower.Contains("engineering") Then
sqlCondition = "where [Engineering] = 1"
End If
ElseIf QCCell.Text.ToLower.Contains("letter") Then
sqlCondition = "where [FinalLetter] = 1"
End If
ddl = New DropDownList
ddl.EnableViewState = True
ddl.AutoPostBack = True
AddHandler ddl.SelectedIndexChanged, AddressOf ddl_selectedIndexChanged
ddl.Width = New Unit(110, UnitType.Pixel)
dropDownListSelect(ddl, nameToSelect, sqlCondition)
reviewerNameCell.Controls.Add(ddl)
End If
End If
End Sub
Protected Sub GridViewAssignment_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridViewAssignment.SelectedIndexChanged
End Sub
Protected Sub dropDownListSelect(ByVal ddlist As DropDownList, ByVal valueToSelect As String, ByVal sqlFilterString As String)
Dim sqlQuery As String = "SELECT [ReviewerName],[Specialty],[Tiger],[Triage]" + _
",[ProgramEligibility],[Engineering],[BCA],[EHP],[QCRole_Level1],[QCRole_Overall]" + _
",[FinalLetter] FROM [SubApplicationTracker].[dbo].[ReviewerResources] " + _
sqlFilterString + " order by ReviewerName asc"
Dim connStr As String = System.Configuration.ConfigurationManager.ConnectionStrings("SubAppTrackerConnString").ConnectionString
Dim sqlconnection As SqlConnection = New SqlConnection(connStr)
sqlconnection.Open()
Dim sqlCommand As SqlCommand = New SqlCommand(sqlQuery, sqlconnection)
Dim dr As SqlDataReader = sqlCommand.ExecuteReader
ddlist.Items.Clear()
ddlist.Items.Add("")
Do While dr.Read
Dim itemToAdd As New ListItem
itemToAdd.Text = dr("ReviewerName")
itemToAdd.Value = dr("ReviewerName")
ddlist.Items.Add(itemToAdd)
Loop
'if we find no reviewer then combo should be at the blank item
If valueToSelect = String.Empty Then
ddlist.Items(0).Selected = True
Else 'if we find a matching value then combo should selected at that value
If ddlist.Items.FindByValue(valueToSelect) IsNot Nothing Then
ddlist.Items.FindByValue(valueToSelect).Selected = True
Else 'if we find a non empty value but it doesnt exist in the combo list then - add that item to combo list and select it
Dim newItem As New ListItem
newItem.Text = valueToSelect
newItem.Value = valueToSelect
ddlist.Items.Add(newItem)
ddlist.Items.FindByValue(valueToSelect).Selected = True
End If
End If
End Sub
You need to be data binding the gridview on every postback, in order to get the event to fire?

Resources