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 strongm 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:
<body>
    <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>
    </body>

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

    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

    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 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.
 
the problem is you're using a datasource control. they are terrible to say the least. drop the datasource control all together and use a data access framework to query the database. the popular ones are:
nhibernate
active record
llbl gen pro ($)
MS data access block

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
not controls, frameworks. data access has nothing to do with controls. controls are only needed for presentation (GUI).

yes, they are 3rd party frameworks. llbl has a small fee. the rest are open source projects.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Is there not a way to natively do this with the built in data access framework?

There may be other ways of doing it with a third party DA framework, but surely there is just something wrong with the way I am using the datasource control and not that the datasource control just doesn't work.
 
the .net framework provides the low level data access components which are ADO.Net. from these components data access frameworks are built. each the frameworks above have an opinion about how to access the database, update records, manage concurrency, etc.

the datasource controls uses ADO.Net as well. why they suck is they are so tightly integrated into the webforms life cycle there is no room to truely customize what you want to do with data access.

there is also the conceptual issue that data access doesn't belong so close to the presenation level anyway. basically you "can" use datasource controls for very simple scenarios, but the minute you want to put logic (in this swapping queries) at runtime they fail miserably.

Jason Meckley
Programmer
Specialty Bakers, Inc.

faq855-7190
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top