从后面的代码访问ListView Evals。获取对象引用未设置为对象的实例

时间:2014-07-18 22:25:42

标签: c# asp.net listview stored-procedures eval

像许多其他人一样,我正在尝试将Eval值分配给ListView外的表中的标签。我正在使用一个存储过程来返回整个城市网站的月降雨量。我想要的字段不是传递的参数之一:@reqyear和@reqLocation。它是一个计算字段Total,它在ListView中显示为Eval,但我无法弄清楚如何直接在代码中访问它,所以我使用ItemDataBound方法找到控件然后分配它。在板上很容易找到几个狙击手。所以我尝试了每个似乎都适用的并且都返回了一个未设置为对象实例的" Object引用"错误。我正在尝试将Eval(" Total")分配给标签ID MTotal。页面运行正常,没有标签分配所需的代码。也许,我正在以错误的方式进行标签分配,并且可以在不使用ListView中的Eval的情况下获得我想要的字段。

感谢任何建议。

code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;



namespace WebApplication1.OUTREACH.rainfall
{
    public partial class monthlyRF : System.Web.UI.Page
    {

    protected void Page_Load(object sender, EventArgs e)
    {


        if (!Page.IsPostBack)
        {
            reqyear.Items.Clear();


            for (int i = DateTime.Now.Year; i != 1998; i--)
            {
                reqyear.Items.Add(i.ToString());
            }

            reqLocation.SelectedValue = "2";
        }

        String strConnString = WebConfigurationManager.ConnectionStrings["TelogerConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(strConnString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.CommandText = "dbo.spBWSC_GetTrendDataMonthly";          
        cmd.Parameters.Add("@req_Location", SqlDbType.VarChar).Value = reqLocation.Text;
        cmd.Parameters.Add("@req_year", SqlDbType.VarChar).Value = reqyear.Text;         
        cmd.Connection = con;


        try
        {
            con.Open();
            ListView1.DataSource = cmd.ExecuteReader();
            ListView1.DataBind();

            yearLabel.Text = reqyear.Text;


            switch (cmd.Parameters["@Req_Location"].Value.ToString())
            {
                case "2":
                    site_nameLabel.Text = "Union Park";
                    break;
                case "3":
                    site_nameLabel.Text = "Roslindale";
                    break;
                case "4":
                    site_nameLabel.Text = "Dorch-Adams";
                    break;
                case "5":
                    site_nameLabel.Text = "Allston";
                    break;
                case "6":
                    site_nameLabel.Text = "Charlestown";
                    break;
                case "7":
                    site_nameLabel.Text = "Longwood";
                    break;
                case "8":
                    site_nameLabel.Text = "Hyde Park";
                    break;
                case "9":
                    site_nameLabel.Text = "Dorch-Talbot";
                    break;

            }


        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();

        }


    }


    protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        Label Total_lbl;
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            Total_lbl = (Label)e.Item.FindControl("Total_lbl");

            DataRowView rowView = e.Item.DataItem as DataRowView;
            string sTotal = rowView["Total"].ToString();
            MTotal.Text = sTotal;

        }
    }


        }

}

ASPX:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="monthlyRF.aspx.cs" Inherits="WebApplication1.OUTREACH.rainfall.monthlyRF" enableEventValidation="false" EnableViewState="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

</head>
<body>

<form id="form1" runat="server">

<asp:RadioButtonList ID="reqLocation" runat="server" Font-Italic="False" 
    Height="100px" RepeatColumns="4" RepeatDirection="Horizontal" Width="590px">
    <asp:ListItem Value="2">Union Park</asp:ListItem>
    <asp:ListItem Value="3">Roslindale</asp:ListItem>
    <asp:ListItem Value="4">Dorch-Adams</asp:ListItem>
    <asp:ListItem Value="5">Allston</asp:ListItem>
    <asp:ListItem Value="6">Charlestown</asp:ListItem>
    <asp:ListItem Value="7">Longwood</asp:ListItem>
    <asp:ListItem Value="8">Hyde Park</asp:ListItem>
    <asp:ListItem Value="9">Dorch_Talbot</asp:ListItem>
</asp:RadioButtonList>



<asp:DropDownList ID="reqyear" runat="server">
</asp:DropDownList>

<asp:Button ID="Button1" runat="server" Text="Submit"  />
 <br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
    ConnectionString="<%$ ConnectionStrings:TelogerConnectionString %>" 
    SelectCommand="spBWSC_GetTrendDataMonthly" SelectCommandType="StoredProcedure" >
    <SelectParameters>
        <asp:ControlParameter ControlID="reqyear" Name="req_year" 
            PropertyName="SelectedValue" Type="String" />
        <asp:ControlParameter ControlID="reqLocation" Name="req_Location" 
            PropertyName="SelectedValue" Type="Int32" />
    </SelectParameters>

</asp:SqlDataSource>

<table border="1" cellpadding="4" cellspacing="0" width="590px" style="margin-top: 25px;">
    <tr>
        <td><asp:Label ID="site_nameLabel" runat="server" />
        </td>
        <td style="text-align:right;"><asp:Label ID="yearLabel" runat="server"/>
        </td>
    </tr>
</table>


<asp:ListView ID="ListView1" runat="server" DataKeyNames="site_name, Total, month, monthly_total" OnItemDataBound="ListView1_ItemDataBound">


    <EmptyDataTemplate>
        <table runat="server" style="">
            <tr>
                <td>
                    No data was returned.</td>
            </tr>
        </table>
    </EmptyDataTemplate>

    <ItemTemplate>
        <tr style="border: 1px solid black;" >
                      <td style="width:245px;">
                 <asp:Label ID="Total_lbl" runat="server" Text='<%# Eval("Total") %>' /></td><td><asp:Label ID="monthLabel" runat="server" Text='<%# Eval("month") %>' />
            </td>
             <td style="text-align:right; width:245px;">
                <asp:Label ID="TotalLabel"  runat="server" Text='<%# Eval("monthly_total", "{0:0.00}") %>' />
            </td>
        </tr>
    </ItemTemplate>
    <LayoutTemplate>
        <table runat="server">
            <tr runat="server">
                <td runat="server">
                    <table ID="itemPlaceholderContainer" runat="server" width="590px">
                        <tr id="header1" runat="server" style="">


                            <th style="text-align:left;" runat="server">
                                Month</th>

                            <th style="text-align:right;" runat="server">
                                Rainfall (in.)</th>

                        </tr>
                        <tr ID="itemPlaceholder" runat="server">

                        </tr>
                    </table>

                </td>
            </tr>
            <tr runat="server">
                <td runat="server" style="">
                </td>
            </tr>
            <tfoot>
            <tr >
            <td colspan="2">this is the listview footer</td>

            </tr>

            </tfoot>
        </table>
    </LayoutTemplate>      
</asp:ListView>
<table border="1" cellpadding="4" cellspacing="0" width="590px" style="margin-top: 0;">
    <tr>
        <td>first cell
        </td>
        <td style="text-align:right;"><asp:Label ID="MTotal" runat="server" Text="Label"/>
        </td>
    </tr>
</table>
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

我怀疑这条线

DataRowView rowView = e.Item.DataItem as DataRowView;

是问题所在。在该行设置断点并调查您到达那里的类型。

如果使用as关键字进行类型转换,则执行转换失败将返回null而不是异常,因此后续调用[&#34; Total&#34;]索引器正在执行空引用。