VB.NET GridView Ignore Null Values in Footer Total - asp.net

VB.net
Protected Sub monthlyReportsUK_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowTotal As Decimal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString)
grdTotal = grdTotal + rowTotal
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lbl As Label = DirectCast(e.Row.FindControl("lblwebsVal"), Label)
lbl.Text = "£" + grdTotal.ToString("##,0.00")
End If
End Sub
HTML:
<asp:TemplateField HeaderText="webShopTotal">
<ItemTemplate>
<asp:Label ID="lblamount" runat="Server" Text='<%# Eval("webShopTotal") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblwebsVal" runat="server"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
GridView
Month Value
Jan NULL
Feb NULL
Mar 15.00
Apr 10.00
I want to be able to sum the values:
Month Value
Jan NULL
Feb NULL
Mar 15.00
Apr 10.00
Total 25.00
However, I am getting the error Object cannot be cast from DBNull to other types.
Is there any way I can add the total in the footer ignoring NULL values?

Try this
Protected Sub monthlyReportsUK_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
If DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString IsNot Nothing AndAlso DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString IsNot DbNull.Value Then
Dim rowTotal As Decimal = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString)
grdTotal = grdTotal + rowTotal
End Id
End If
If e.Row.RowType = DataControlRowType.Footer Then
Dim lbl As Label = DirectCast(e.Row.FindControl("lblwebsVal"), Label)
lbl.Text = "£" + grdTotal.ToString("##,0.00")
End If
End Sub
Edit
First, you should always use System.Decimal.TryParse() instead of Convert.ToDecimal()
Dim result = 0
Dim rowTotal As Decimal = Decimal.TryParse(DataBinder.Eval(e.Row.DataItem, "webShopTotal").ToString), out result)

Related

Get the value of selected item in dropdownlist

I added Item in dropdownlist and when I select the Item I added, it does not show up in Label1. Here is my code:
ASPX
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:DropDownList ID="drpOne" runat="server" AutoPostBack="true">
</asp:DropDownList>
VB
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
con.Open()
If Not IsPostBack Then
Dim Sql = "SELECT College FROM College"
cmdAdd = New SqlDataAdapter(Sql, con)
Dim ds As New DataSet()
cmdAdd.Fill(ds)
drpOne.DataSource = ds
drpOne.DataTextField = "College"
drpOne.DataValueField = "College"
drpOne.DataBind()
drpOne.Items.Insert(0, New ListItem("Please select College", ""))
drpOne.SelectedItem.Value = "Please select College"
drpOne.Items.Insert(0, New ListItem("All", ""))
end if
End Sub
Protected Sub drpOne_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpOne.SelectedIndexChanged
Label1.Text = drpOne.SelectedItem.Value
End Sub
i haven't checked the code, but try it this way
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
con.Open()
If Not IsPostBack Then
Dim Sql = "SELECT College FROM College"
cmdAdd = New SqlDataAdapter(Sql, con)
Dim ds As New DataSet()
cmdAdd.Fill(ds)
drpOne.AppendDataBoundItems = true
drpOne.Add(New ListItem("Please select College", ""))//You have passed "Please select College" as text and "" as value in ListItem
drpOne.Add(New ListItem("All", ""))
drpOne.DataSource = ds
drpOne.DataTextField = "College"
drpOne.DataValueField = "College"
drpOne.DataBind()
drpOne.Items.FindByText("Please select College").Selected = true
end if
End Sub
Protected Sub drpOne_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles drpOne.SelectedIndexChanged
Label1.Text = drpOne.SelectedItem.Value
End Sub
drpOne.SelectedItem.Text == "enter the value which you want to search"
DataValueField must set your primary key column Id , I think CollegeId is that .
drpOne.DataTextField = "College"
drpOne.DataValueField = "CollegeId"//Must set Integer value for dropdown item vale

Integer column in GridView is being sorted as a string

I have a GridView, which has a column as shown below:
<asp:TemplateField HeaderText="Vendor Path" SortExpression="DocumentTemplateFieldID" ItemStyle-HorizontalAlign="Center" HeaderStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Label ID="vendor" Height="10px" Width="60px" runat="server" Text='<%# Eval("DocumentTemplateFieldID") %>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
I allow sorting; however, it sorts it as if it were a string. In the database, it is an integer column.
How do I make my GridView accept that I'm really putting integers in there? I tried to convert it and that didn't work.
Code added:
Protected Sub TaskGridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles GridView1.Sorting
dsData = Session("dataTableView")
Dim sortExpression As String = e.SortExpression
Dim direction As String = String.Empty
If SortDirection = SortDirection.Ascending Then
SortDirection = SortDirection.Descending
direction = " DESC"
Else
SortDirection = SortDirection.Ascending
direction = " ASC"
End If
Dim table As DataTable = dsData
table.DefaultView.Sort = sortExpression + direction
GridView1.DataSource = table
GridView1.DataBind()
Session("dataTableView") = table
End Sub
Private Property SortDirection() As SortDirection
Get
If Session("sortDir") = Nothing Then
Session("sortDir") = SortDirection.Ascending
End If
Return CType(Session("sortDir"), SortDirection)
End Get
Set(ByVal value As SortDirection)
Session("sortDir") = value
End Set
End Property
Updated:
Public Function initialQuery(ByVal vendorID As String) As DataTable
Dim objConn As IDbConnection = Nothing
Dim dsData As New DataTable
Dim objParams(0) As IDbDataParameter
Try
objConn = DBAccess.GetConnection
objParams(0) = DBAccess.CreateParameter("DWSVendorID", DbType.String, vendorID, ParameterDirection.Input)
'Need to figure out how to add the below code:
If (Not IsNothing(vendorID) And Not vendorID = 0) Then
' strBlder.Append("WHERE B.DocumentProviderID = '" + vendorID.ToString + "' ")
End If
dsData = DBAccess.ExecuteDataTable(objConn, DataAccessHelper.Schema & "LLC.[DWSMappingToolInitialQuery]", objParams)
Finally
If Not objConn Is Nothing Then
DBAccess.CloseConnection(objConn)
End If
End Try
If dsData.Rows.Count > 0 Then
Return dsData
End If
Return Nothing
End Function

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?

How to multiply textbox with gridview columns

I have write this code to create a gridview with 3 columns
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price(Grouch)/Hectares", typeof(float));
DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["ID"];
dt.PrimaryKey = keys;
dt.Rows.Add("1", "Seaside Location", 1.5);
Session[key] = dt;
return dt;
I would like to add in this code a textbox with the quantity.
When i give the quantity i want in another textbox to have the total.
for example 2*1.5=3
How can i do that?
My huge problem is that i dont know how to take the values of the 3rd column.The value 1.5 in this example.
If i've understood you correctly, you want a TextBox in the price-column and a textbox for the total price. You could use a TemplateColumn to show the price in a textbox and the footer to show the totalprice.
ASPX:
<asp:GridView ID="GridView1" runat="server" ShowFooter="true" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField HeaderText="ID" DataField="Name" />
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:TemplateField HeaderText="Price(Grouch)/Hectares">
<ItemTemplate>
<asp:TextBox ID="TxtPrice" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtTotal" runat="server" Text="0"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Sorry for VB.Net, i hope you see what i mean anyway, the importan part is in RowDataBound of the GridView:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim dt As New DataTable
dt.Columns.Add("ID", GetType(Int32)).AutoIncrement = True
dt.Columns.Add("Name", GetType(String))
dt.Columns.Add("Price(Grouch)/Hectares", GetType(Single))
dt.PrimaryKey = New DataColumn() {dt.Columns("ID")}
Dim newRow As DataRow = dt.NewRow
newRow("ID") = 1
newRow("Name") = "Seaside Location"
newRow("Price(Grouch)/Hectares") = 1.5
dt.Rows.Add(newRow)
newRow = dt.NewRow
newRow("ID") = 2
newRow("Name") = "City Location"
newRow("Price(Grouch)/Hectares") = 7.9
dt.Rows.Add(newRow)
Me.GridView1.DataSource = dt
Me.GridView1.DataBind()
End Sub
Private totalPrice As Single = 0
Private Sub GridRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim row As DataRow = DirectCast(e.Row.DataItem, DataRowView).Row
Dim txtPrice As TextBox = DirectCast(e.Row.FindControl("TxtPrice"), TextBox)
Dim price As Single = DirectCast(row("Price(Grouch)/Hectares"), Single)
txtPrice.Text = price.ToString
totalPrice = totalPrice + price
ElseIf e.Row.RowType = DataControlRowType.Footer Then
Dim txtTotal As TextBox = DirectCast(e.Row.FindControl("TxtTotal"), TextBox)
txtTotal.Text = totalPrice.ToString
End If
End Sub
To get the value from the third column you can iterate over that array:
GridView.Rows[index].Cells[2].Value.ToString());
Example:
String TextIn4thRow3rdColumn = myGridView.Rows[3].Cells[2].Value.ToString());

Resources