Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Datagrid and SqlDataSource issue

Status
Not open for further replies.

ljwilson

Programmer
May 1, 2008
65
US
I am trying to change the datasource of a GridView and then show the rows. It works perfectly when the Grid is loaded the first time, however when I do something to change the datasource, I get a "object reference not set to an instance of an object" error.

I still get the grid to update either way, just when I select a row (to view a document), I get the error unless the Grid is first loaded.

Here is the Grid Definition & SqlDataSource Definition in the aspx file:
Code:
    <form id="form1" runat="server">
        <table cellpadding="0" cellspacing="0" width="100%">
        <% Try%>
        
        <!--#include file ="header.inc"-->
        
        <%  Catch ex As Exception
                Me.lblMessage.Text = "Authentication Error. Please logoff and back on."
            End Try
        %>
        
        </table>
        <asp:Label ID="Label2" runat="server"></asp:Label>
        <table width="100%">
            <tr>
                <td align="center" colspan="4">
                    <asp:Label ID="Label1" runat="server" SkinID="title" Text="All Documents"></asp:Label></td>
            </tr>
            <tr>
                <td class="style1">
                    &nbsp;</td>
                <td colspan="3">
                </td>
            </tr>
            <tr>
                <td class="style1">Filter By:</td>
                <td class="style2">
                    <asp:DropDownList ID="FilterDropDown" runat="server" Height="20px" Width="222px" AutoPostBack="True" OnSelectedIndexChanged="FilterDropDown_SelectedIndexChanged">
                        <asp:ListItem Value="ALL">ALL</asp:ListItem>
                        <asp:ListItem Value="Check Request">Check Request</asp:ListItem>
                        <asp:ListItem Value="Invoice">Invoice</asp:ListItem>
                        <asp:ListItem Value="W9">W9</asp:ListItem>
                        <asp:ListItem Value="Receipt">Receipt</asp:ListItem>
                        <asp:ListItem Value="Budget">Budget</asp:ListItem>
                        <asp:ListItem Value="Consent">Consent Form</asp:ListItem>
                        <asp:ListItem Value="HIPAA">HIPAA</asp:ListItem>
                    </asp:DropDownList>
                </td>
                <td class="style3">
                    <asp:TextBox ID="SearchTextBox" runat="server" Width="327px"></asp:TextBox>
                </td>
                <td>
                    <asp:Button ID="SearchButton" runat="server" Text="Search" Width="80px" />
                </td>
            </tr>
        </table>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="fileNewName"
            DataSourceID="SqlDataSource_Filter"  AllowSorting="True" Width="100%">
            <Columns>
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="fileOldName" HeaderText="File Name" SortExpression="fileOldName" />
                <asp:BoundField DataField="fileDescription" HeaderText="Description" SortExpression="fileDescription" />
                <asp:BoundField DataField="createDate" HeaderText="Upload Date" SortExpression="createDate" />
                <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" SortExpression="id" Visible="true" />
           </Columns>            
        </asp:GridView>
        <asp:SqlDataSource ID="SqlDataSource_Filter" runat="server" ConnectionString="<%$ ConnectionStrings:ClinicalTrialsConnectionString %>"
            SelectCommand="sp_getDocumentList_Filtered" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:Parameter Name="FilterBy" Type="String" DefaultValue="All" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:SqlDataSource ID="SqlDataSource_Search" runat="server" ConnectionString="<%$ ConnectionStrings:ClinicalTrialsConnectionString %>"
            SelectCommand="sp_getDocumentList_Search" SelectCommandType="StoredProcedure">
            <SelectParameters>
                <asp:Parameter Name="SearchCriteria" Type="String" DefaultValue="All" />
            </SelectParameters>
        </asp:SqlDataSource>
        <asp:Label ID="lblMessage" runat="server" SkinID="error" Text=""></asp:Label><br />
        <br />
        <!--#include file ="footer.inc"-->
    
    </form>


Here is the CodeBehind:
Code:
Partial Public Class viewDocuments
    Inherits System.Web.UI.Page
    
    Private Sub SqlDataSource_Filter_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource_Filter.Selecting

    End Sub

    Protected Sub SqlDataSource_Search_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource_Search.Selecting
        
    End Sub

    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GridView1.SelectedIndexChanged
        Dim localFileName As String = ""
        Dim originalFilename As String
        Dim userId As String
        Dim userPw As String
        Dim userDomain As String

        Try
            GridView1.DataBind()
            localFileName = My.Settings.DocumentPath.ToString + Me.GridView1.SelectedDataKey.Value.ToString
            originalFilename = Me.GridView1.SelectedRow.Cells(1).Text
            userId = My.Settings.DocumentUserId.ToString
            userPw = My.Settings.DocumentUserPw.ToString
            userDomain = My.Settings.DocumentUserDomain.ToString

            Dim Impersonate As New Impersonation.Impersonate      'Instantiate the class into a variable

            Dim User As System.Security.Principal.WindowsImpersonationContext
            User = Impersonate.ImpersonateUser(userId, userPw, userDomain)   'Start the Impersonation

            Dim liveStream As New System.IO.FileStream(localFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read)

            Dim buffer As Byte() = New Byte(CInt(liveStream.Length) - 1) {}
            liveStream.Read(buffer, 0, CInt(liveStream.Length))
            liveStream.Close()

            Response.Clear()
            Response.ContentType = "application/octet-stream"
            Response.AddHeader("Content-Length", buffer.Length.ToString())
            Response.AddHeader("Content-Disposition", "attachment; filename=" + originalFilename)
            Response.BinaryWrite(buffer)
            Response.End()

            Impersonate.UndoImpersonate(User)   'Kill the Impersonation

        Catch etax As Threading.ThreadAbortException
            ' Do Nothing
        Catch ex As Exception
            Try
                Me.lblMessage.Text = "Error " + ex.Message
                Dim dataAccess As New DAO
                Dim parameters As String = "accountId " + Request.QueryString("accountId") + " localFileName " + localFileName
                dataAccess.insertErrorLog(parameters, "Document Centert GridView1_SelectedIndexChanged", ex.Message, ex.ToString, Server.UrlDecode(Request.Cookies("authenticated")("user").ToString), Context.Request.UserHostAddress.ToString)
            Catch ex1 As Exception
                Response.Write("ERROR: " + ex1.ToString)
            End Try
        End Try


    End Sub

    Protected Sub FilterDropDown_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles FilterDropDown.SelectedIndexChanged
        Dim FilterValue As String
        
        FilterValue = FilterDropDown.SelectedItem.Value
        
        With SqlDataSource_Filter
            .SelectParameters("FilterBy").DefaultValue = FilterValue
            .SelectCommand = "sp_getDocumentList_Filtered"
            .DataBind()
        End With


        With GridView1
            .DataSourceID = Nothing
            .DataSource = SqlDataSource_Filter
            .DataBind()
            .SelectedIndex = -1
        End With
    End Sub

    Private Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load

        ' Have to set visibility to true until after data is bound due to GridViews 
        ' inability to get value of hidden column cells
        With GridView1
            .Columns(4).Visible = True
            .DataBind()
            .Columns(4).Visible = False
        End With

        Dim mid As String = ""
        Try
            mid = Server.UrlDecode(Request.Cookies("authenticated")("user").ToString)
        Catch ex As Exception
            Response.Redirect("login.asp", False)
        End Try
        
    End Sub

    Protected Sub SearchButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SearchButton.Click

        Dim Criteria As String

        Criteria = SearchTextBox.Text
        
        With SqlDataSource_Search
            .SelectCommand = "sp_getDocumentList_Search"
            .SelectParameters("SearchCriteria").DefaultValue = Criteria
            .DataBind()
        End With

        With GridView1
            .DataSourceID = Nothing
            .DataSource = SqlDataSource_Search
            .DataBind()
            .SelectedIndex = -1
        End With
    End Sub

    Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
        GridView1.PageIndex = e.NewPageIndex
        GridView1.DataBind()
    End Sub
End Class

I have tried several things with no success. Please help.

 
ljwilson,

Please post your question here:
forum855

The ASP.Net forum gets ASP.Net questions for ASP.Net regardless if the code-behind language is VB or C#. The VB.Net forum gets more questions and answers for VB.Net in Windows Forms/Windows Services/Console Apps/VB syntax.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top