System.NullReferenceException: Object reference not set to an instance of an object [duplicate]

1

I'm making a simple query to DB and it gives me the error of the title.

It tells me that the error is in if(reader.Read())

I have this in the aspx:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" '
SelectCommand="SELECT [Articulos].[codigo], [Articulos].[descripcion], [Articulos].[precio], [Articulos].[codigoRubro], [Rubros].[descripcion]
FROM [Articulos] JOIN [Rubros] ON [Articulos].[codigoRubro] = [Rubros].[codigo] WHERE [Articulos].[descripcion]=@descripcion">
        <SelectParameters>
            <asp:Parameter Name="codigo" />
            <asp:Parameter Name="descripcion" />
            <asp:Parameter Name="precio" />
            <asp:Parameter Name="codigoRubro" />
            <asp:Parameter Name="descripcionRubro" />
        </SelectParameters>
    </asp:SqlDataSource>

and this in the cs:

try
{
    SqlDataSource1.SelectParameters["descripcion"].DefaultValue = txbxArticleName.Text.ToUpper().Trim();
    SqlDataSource1.DataSourceMode = SqlDataSourceMode.DataReader;
    SqlDataReader reader = (SqlDataReader)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

    **if (!reader.Read())
    {**
        panelResult.Visible = true;

        txbxNameResult.Text = reader["descripcion"].ToString().Trim();
        txbxCodeResult.Text = reader["codigo"].ToString().Trim();
        txbxPriceResult.Text = reader["precio"].ToString().Trim();
        txbxProductCodeResult.Text = reader["codigoRubro"].ToString().Trim();
    }

Obviously, this is because reader is null . So, my question is: Why is null and how can I solve it?

    
asked by Joam Delgado 31.03.2017 в 15:21
source

1 answer

0

If you check the documentation

SqlDataSource.Select Method

you could get a DataView , using:

DataView dv = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);

if (dv.Table.Rows.Count > 0){
   var row = dv.Table.Rows[0];

   txbxNameResult.Text = row["descripcion"].ToString().Trim();
   //resto
}

in this way valid if the command and data can be recovered, or if the problem is something more general

    
answered by 31.03.2017 в 17:42