Help: Error = NullReferenceException was unhandled by user code - asp.net

Any help would be appreciated... Code works cleanly until error...
Error occuring at line: SqlDataSource3.UpdateParameters("TechID").DefaultValue() = CInt(technicianRow("TechID"))
Here is full VB code:
Imports System.Data
Partial Class IncidentAssignment
Inherits System.Web.UI.Page
Public incidentRow As DataRowView
Public technicianRow As DataRowView
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
'Check to see if a incident has been selected
If GridView1.SelectedIndex = -1 Then
Button1.CommandName = ""
lblmessage.Text = "You must select an incident."
Else
Button1.CommandName = "NextView"
lblmessage.Text = ""
End If
End Sub
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
'Check to see if a incident has been selected
If GridView2.SelectedIndex = -1 Then
Button3.CommandName = ""
lblmessage2.Text = "You must select a technician."
Else
Button3.CommandName = "NextView"
lblmessage2.Text = ""
'Create second DataView
Dim techniciansTable As DataView = CType(SqlDataSource2.Select(DataSourceSelectArguments.Empty), DataView)
'Save the selected technician data row
'To the DataRowView object and to session state
technicianRow = techniciansTable(GridView2.SelectedIndex)
Session("Technician") = technicianRow
'Create DataView
Dim incidentsTable As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
'Save PageIndex and PageSize to variables.
Dim pageIndex As Integer = GridView1.PageIndex
Dim pageSize As Integer = GridView1.PageSize
'Calculate the value of the SelectedIndex
Dim selectedIndex As Integer = (pageIndex * pageSize) + GridView1.SelectedIndex
'Save the selected data row to the DataRowView
'object and to session state
incidentRow = incidentsTable(selectedIndex)
Session("Incident") = incidentRow
'Display output from the two DataRowView objects
Label1.Text = incidentRow("Name")
Label2.Text = incidentRow("ProductCode")
Label3.Text = technicianRow("Name")
End If
End Sub
Public Sub btnAssign_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAssign.Click
'Assign data from session state to
'the two DataRowView objects
***ERROR technicianRow = CType(Session("Technician"), DataRowView)
incidentRow = CType(Session("Incident"), DataRowView)
'Update the value of the two parameters to be
'used to store new information about the
'assigned technician
SqlDataSource3.UpdateParameters("TechID").DefaultValue() = CInt(technicianRow("TechID"))
SqlDataSource3.UpdateParameters("IncidentID").DefaultValue() = CInt(incidentRow("IncidentID"))
'Trap errors
Try
'Update the table.
SqlDataSource3.Update()
'Unselect the two GridView controls
GridView1.SelectedIndex = -1
GridView2.SelectedIndex = -1
'Rebind the GridView controls
GridView1.DataBind()
GridView2.DataBind()
'Move to the first view
MultiView1.ActiveViewIndex = 0
Catch ex As Exception
Session("Exception") = ex
Session("Page") = "~/Admin/IndicentAssignment.aspx"
Response.Redirect("~/ErrorMessage.aspx")
End Try
End Sub
Protected Sub GridView2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView2.SelectedIndexChanged
End Sub
End Class

Remove the parenthesis from ".DefaultValue()
do you have the parameters defined on the sqldatasource in the page??
UpdateParameters>
<asp:Parameter Name="SomeName" Type="String" />
<asp:Parameter Name="SomeDescription" Type="String" />
</UpdateParameters>

Related

Why System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative is occuring when i change the page no. in gridview

Index was out of range. Must be non-negative and less than the size of the collection.This error is showing if I change the page number in grid view.In first page every rows are working correctly but after first page if I click on any row it is showing the error.
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
For Each row As GridViewRow In GridView_modify.Rows
If row.RowType = DataControlRowType.DataRow Then
row.Attributes("onmouseover") = "this.style.cursor='hand';this.style.textDecoration='underline';"
row.Attributes("onmouseout") = "this.style.textDecoration='none';"
row.Attributes("onclick") = ClientScript.GetPostBackClientHyperlink(GridView_modify, "Select$" & row.DataItemIndex, True)
Next
MyBase.Render(writer)
End Sub
Protected Sub GridView_modify_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView_modify.SelectedIndexChanged
PanelModify.Visible = True
connection.ConnectionString = connectionstringdb
Try
connection.Open()
Dim row As GridViewRow = GridView_modify.SelectedRow
test1 = DirectCast(GridView_modify.SelectedRow.Cells(1).FindControl("HiddenField1"), HiddenField).Value
lbl_slno.Text = test1
selectAllFieldsUpdate()
txt_tenderDate_update.Text = GridView_modify.SelectedRow.Cells(2).Text ' or 'Text1.Value = row.Cells[1].Text;
txt_sub_update.Text = GridView_modify.SelectedRow.Cells(1).Text
txt_lastdate_udpate.Text = GridView_modify.SelectedRow.Cells(3).Text
Catch ce As Exception
Response.Write(ce.ToString())
Finally
connection.Close()
End Try
connection.Close()
End Sub
Protected Sub GridView_modify_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles GridView_modify.PageIndexChanged
Filldatagrid()
End Sub
Protected Sub GridView_modify_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView_modify.PageIndexChanging
GridView_modify.PageIndex = e.NewPageIndex
End Sub
Public Sub Filldatagrid()
connection.ConnectionString = connectionstringdb
Try
connection.Open()
Dim strsql1 As String = ("SELECT SlNo,Subject,convert(varchar(10),[TenderDate],105) as TenderDate,convert(varchar(10),[Lastdate],105) as Lastdate,Filename from TenderTable order by convert(datetime, Tenderdate, 105) Desc")
Dim mydatadapter As New SqlDataAdapter(strsql1, connection)
Dim mydataset As New DataSet
mydatadapter.Fill(mydataset, "TenderTable")
GridView_modify.DataSource = mydataset.Tables("TenderTable")
GridView_modify.DataBind()
connection.Close()
Catch ex As Exception
Response.Write(ex.ToString())
connection.Close()
End Try
End Sub

ASP VB Stuck on Dynamic Controls, Viewstate, and Postback. Could really use some help to get back on track

I've been reading posts and articles and just getting a little confused and consequently burning through time I don't have at the moment
Can someone look at my code and tell me where I've gone wrong?
Partial Class PayerContacts
Inherits System.Web.UI.Page
Dim connStrDRContacts As String = ConfigurationManager.ConnectionStrings("DRContacts_SQL").ConnectionString
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
navBuild()
End Sub
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
If IsPostBack Then
LoadContacts(ViewState("objSender"))
End If
End Sub
Private Function navBuild() As Integer
Dim SQLstrDRs As String = "SELECT * FROM DRList"
Dim DbConnDRs As SqlConnection = New SqlConnection(connStrDRContacts)
DbConnDRs.Open()
Dim dtDRsTemp As New DataTable
Dim SQLAdapterDRs As New SqlDataAdapter(SQLstrDRs, DbConnDRs)
SQLAdapterDRs.Fill(dtDRsTemp)
'Loop through each row of the DataView to create HTML table data
Dim NewTableRow As New TableRow
For Each row As DataRow In dtDRsTemp.Rows
'CREATE table with button to display contacts related to client (one to many)
Dim NewTableButton As LinkButton = New LinkButton
NewTableButton.ID = "btnDRName" & NewTableText
NewTableButton.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler NewTableButton.Click, AddressOf LoadContacts
Next
Return 0
End Function
Protected Sub LoadContacts(sender As Object, e As EventArgs)
Dim LoopCount As Integer = 0
Dim SQLstrLoadTable As String = "SELECT * FROM ContactList WHERE DRVendor = '" & sender.Text.ToString & "'"
and so on....
SQLAdapterLoadTable.Fill(dtLoadTableTemp)
Dim NewTableRow As New TableRow
For Each row As DataRow In dtLoadTableTemp.Rows
'CREATE Accordion to display data
NewAccordion.ID = "ContactAccordion" & LoopCount
NewAccordion.Visible = True
blah, blah...
'SET Pane
NewAccordionPane.HeaderContainer.ID = "PaneHeader" & LoopCount
NewAccordionPane.ContentContainer.ID = "PaneContent" & LoopCount
'CREATE button to open ModalPopup to EDIT each record
Dim imgGear As New ImageButton
imgGear.ID = "btnGear" & row!ID.ToString
imgGear.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler imgGear.Click, AddressOf EditRecord
'LOAD Pane
NewAccordionPane.HeaderContainer.Controls.Add(NewHeaderTable)
NewAccordionPane.ContentContainer.Controls.Add(New LiteralControl(NewTableText))
ViewState("objSender") = sender
End Sub
Protected Sub EditRecord(ByVal sender As Object, ByVal e As EventArgs)
'Open ModalPopup to edit record
popup.Show()
pnlAddEdit.Visible = True
End Sub
End Class
The Infinities Loop articles on ViewState and Dynamic Controls should really be read by every Webforms developer: -
http://mocha.mojoskins.com/SharedFiles/Download.aspx?pageid=566&mid=786&fileid=38
http://weblogs.asp.net/infinitiesloop/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_
The examples are in C# but you should be able to figure out what's going on, it's the same base class library after all.

Editing a Gridview w/o using an SqlDatasource using VB.Net

I developed the following code for editing a GridView (following a tutorial written in C#), It goes into edit mode, but my edits do not take effect, here is my code:
aspx.vb code:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Globalization
Partial Class MemberPages_editOutage
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim dt As New DataTable()
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Try
connection.Open()
Dim sqlStatement As String = "SELECT OutageDetailId, LocationName, Description, DetailDescription, CreateDate, StatusId FROM OutageDetail WHERE StatusId='1' ORDER BY CreateDate DESC"
Dim cmd As New SqlCommand(sqlStatement, connection)
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
MyDataGrid.DataSource = dt
MyDataGrid.DataBind()
End If
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Fetch Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
connection.Close()
End Try
End Sub
'edit command
Protected Sub MyDataGrid_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles MyDataGrid.RowEditing
'turn to edit mode
MyDataGrid.EditIndex = e.NewEditIndex
'Rebind the GridView to show the data in edit mode
BindGrid()
End Sub
'cancel command
Protected Sub MyDataGrid_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles MyDataGrid.RowCancelingEdit
' switch back to edit default mode
MyDataGrid.EditIndex = -1
'Rebind the GridView to show the data in edit mode
BindGrid()
End Sub
'Update Function
Private Sub UpdateRecord(ByVal SOutageDetailId As String, ByVal SDescription As String, ByVal SDetailDescription As String, ByVal SCreateDate As String, ByVal SstatusId As String)
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Dim sqlStatement As String = String.Empty
sqlStatement = "UPDATE OutageDetail SET #OutageDetailId = #OutageDetailId, LocationName = #LocationName, " & _
"Description = #Description, DetailDescription= #DetailDescription, " & _
"CreateDate = #CreateDate, StatusId = #StatusId WHERE OutageDetailId = #OutageDetailId"
connection.Open()
Dim cmd As New SqlCommand(sqlStatement, connection)
cmd.Parameters.Add(New SqlParameter("#OutageDetailId", SOutageDetailId))
cmd.Parameters.Add(New SqlParameter("#LocationName", SDescription))
cmd.Parameters.Add(New SqlParameter("#Description", SDescription))
cmd.Parameters.Add(New SqlParameter("#DetailDescription", SDetailDescription))
cmd.Parameters.Add(New SqlParameter("#CreateDate", SCreateDate))
cmd.Parameters.Add(New SqlParameter("#StatusId", SstatusId))
cmd.CommandType = CommandType.Text
cmd.ExecuteNonQuery()
' MyDataGrid.EditIndex = -1
connection.Close()
BindGrid()
End Sub
'update command
Protected Sub MyDataGrid_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles MyDataGrid.RowUpdating
'Accessing Edited values from the GridView
Dim SOutageDetailId As String = MyDataGrid.Rows(e.RowIndex).Cells(0).Text
Dim SDescription As String = MyDataGrid.Rows(e.RowIndex).Cells(1).Text
Dim SDetailDescription As String = MyDataGrid.Rows(e.RowIndex).Cells(2).Text
Dim SCreateDate As String = MyDataGrid.Rows(e.RowIndex).Cells(3).Text
Dim SstatusId As String = MyDataGrid.Rows(e.RowIndex).Cells(4).Text
'Call the function to update the GridView
UpdateRecord(SOutageDetailId, SDescription, SDetailDescription, SCreateDate, SstatusId)
MyDataGrid.EditIndex = -1
'Rebind Gridview to reflect changes made
BindGrid()
End Sub
End Class
aspx code:
<asp:GridView id="MyDataGrid" runat="server"
Width="750px"
CssClass="gridViewEdit"
BackColor="White"
BorderColor="Black"
CellPadding="3"
Font-Name="Verdana"
Font-Size="8pt"
HeaderStyle-BackColor="#FFFFFF"
OnEditCommand="MyDataGrid_RowEditing"
OnCancelCommand="MyDataGrid_RowCancelingEdit"
OnUpdateCommand="MyDataGrid_RowUpdating"
DataKeyField="OutageDetailId"
Font-Names="Verdana">
<Columns>
<asp:CommandField ShowEditButton="True" EditText="Edit" CancelText="Cancel" UpdateText="Update" />
</Columns>
<HeaderStyle BackColor="White"></HeaderStyle>
</asp:GridView>
Could someone shed some light on what I am missing please.
The moment you hit the Edit, you go to get the ID of the line that must be update, and you get it from this line
Dim SOutageDetailId As String = MyDataGrid.Rows(e.RowIndex).Cells(0).Text
but on page load you have set
If Not IsPostBack Then
BindGrid()
End If
so on the post back, the grid up to the point you try to get the id from the cell, is empty.
Two ways, ether give again the data on post back, and make DataBind right after the update, or get the Index of the Grid View to make the Update, and not take the Cell.
For example, I will change your code to:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
BindGrid()
End Sub
Private Sub BindGrid()
Dim dt As New DataTable()
Dim connection As New SqlConnection("server='\SQLEXPRESS'; trusted_connection='true'; Database='OutagesMgt_db'")
Try
connection.Open()
Dim sqlStatement As String = "SELECT OutageDetailId, LocationName, Description, DetailDescription, CreateDate, StatusId FROM OutageDetail WHERE StatusId='1' ORDER BY CreateDate DESC"
Dim cmd As New SqlCommand(sqlStatement, connection)
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
MyDataGrid.DataSource = dt
If Not IsPostBack Then
MyDataGrid.DataBind()
End If
End If
Catch ex As System.Data.SqlClient.SqlException
Dim msg As String = "Fetch Error:"
msg += ex.Message
Throw New Exception(msg)
Finally
connection.Close()
End Try
End Sub
[*] Assuming that you do not have other bugs on sql...

how to highlight the biggest value in a Gridview

I have a gridview that is binded.
And i want to change the color of the font for the longest leadtime even if there are duplicates. I have no idea on how to write my if statement.
This is a rough idea of what i want to do, though I know this code is wrong.
if Max(LeadTime) Then
GridView.ForeColor = Color.Red
Can anyone help me?
You first need to get the max value from your datasource. You can do this with linq:
maxLeadTime = ds.Max(dsi => dsi.LeadTime)
In your item data bound event handler, compare the bound item with the max value:
if (item.LeadTime == maxLeadTime)
{
/* do stuff */
}
(VB.NET version) Assuming you are binding you Grid to a datatable, this is how you will do it.
Private maxVal As Decimal
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Me.Page.IsPostBack Then
dim dt as datatable = GetTable()
maxVal = ds.AsEnumerable.Max(Function(dr) dr("lead_time"))
gv.DataSource = dt
gv.DataBind()
End If
End Sub
Private Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gv.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim dr As DataRowView = e.Row.DataItem
If dr("lead_time") = maxVal Then
e.Row.BackColor = Drawing.Color.Red
End If
End If
End Sub
it would be the same if you are binding it to a list(of T)
In PAge Load:
maxVal = urList.Max(Function(x) x.LeadTime)
In Row dataBound:
Dim uc As urClass = e.Row.DataItem
If uc.LeadTime = maxVal Then
e.Row.BackColor = Drawing.Color.Red
End If

viewState value is not shown after first postback

I'm new to asp.net (after programming for years in classic asp). I'm trying to build a page which adds something to a string.
My code is following:
default.aspx
<body>
<form id="form1" runat="server">
<div>
<p><asp:textbox id="tb" runat="server"></asp:textbox></p>
<asp:Panel ID="tbPanel" runat="server"></asp:Panel>
</div>
</form>
</body>
Code behind:
Partial Class demo_Default
Inherits System.Web.UI.Page
Public Property gesStr As String
Set(value As String)
ViewState("gesStr") = value
End Set
Get
Dim o As Object = ViewState("gesStr")
If o Is Nothing Then
Return ""
Else
Return o
End If
End Get
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim anzeigeStr As String = ""
If Page.IsPostBack Then
Else
gesStr = "1;"
End If
tb.Text = gesStr
Dim iButton As New Button
iButton.Text = "add"
iButton.CommandArgument = "1;"
AddHandler iButton.Click, AddressOf add
tbPanel.Controls.Add(iButton)
Me.anzeige()
End Sub
Private Sub add(ByVal sender As Object, ByVal e As EventArgs)
Dim myButton As Button = DirectCast(sender, Button)
Dim addString As String = myButton.CommandArgument
gesStr += addString
End Sub
Private Sub anzeige()
Dim gesArray As Array = Split(gesStr, ";")
For xLauf As Integer = 0 To UBound(gesArray) - 1
Dim anzLabel As New Label
anzLabel.Text = "<p>" & gesArray(xLauf) & "</p>"
tbPanel.Controls.Add(anzLabel)
Next
End Sub
End Class
The problem:
Pressing the button will cause a postBack, but the result of adding won't appear until the button is pressed a second time. The desired result is that the sub displays the correct array within the loop after the first time pressing the button.
Thank you so much for any help!
You need to call the function anzeige() and bind gesStr value to the textbox control each time the button is click. See the code below:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
Else
gesStr = "1;"
End If
tb.Text = gesStr
Dim iButton As New Button
iButton.Text = "add"
iButton.CommandArgument = "1;"
iButton.CommandName = "1;"
AddHandler iButton.Click, AddressOf add
tbPanel.Controls.Add(iButton)
End Sub
Private Sub add(ByVal sender As Object, ByVal e As EventArgs)
Dim myButton As Button = DirectCast(sender, Button)
Dim addString As String = myButton.CommandArgument
gesStr += addString
anzeige()
End Sub
Private Sub anzeige()
Dim gesArray As Array = Split(gesStr, ";")
For xLauf As Integer = 0 To UBound(gesArray) - 1
Dim anzLabel As New Label
anzLabel.Text = "<p>" & gesArray(xLauf) & "</p>"
tbPanel.Controls.Add(anzLabel)
Next
'Bind gesStr value to the textbox control
tb.Text = gesStr
End Sub

Resources