2017-01-17 13 views
-3

aspx.csページでNullrefernceExceptionを取得していますが、既にaspxページのラベルにテキストを割り当てています。最初はセッションだと思っていましたが、ログインしても同じエラーが出ます。私は自分のデータベースとスペルをチェックしていると間違って何もありませんラベルにテキストが割り当てられていてもNullreferenceexceptionを取得する際にエラーが発生する

マイaspx.csコード:aspxページ内

protected void Page_Load(object sender, EventArgs e) 
{ 
    Label Lefthowmanylabel =(Label)DataList1.FindControl("Lefthowmanylabel"); 
    Label quantitylabel = (Label)DataList1.FindControl("quantitylabel"); 


    if (int.Parse(quantitylabel.Text) < 11) 
    { 
     Lefthowmanylabel.Visible = true; 
    } 
    else 
    { 
     Lefthowmanylabel.Visible = false; 
    } 


} 

私のDataList項目:あなたがアクセスをアクセスしたい場合は

<asp:Label ID="Lefthowmanylabel" runat="server" Text="Only 10 Left!! While stock last!" Visible="False"/> 
<asp:Label ID="quantitylabel" runat="server" Text='<%# Eval("Quantity") %>' Visible="False" /> 
       </td> 
+3

の可能性のある重複した[何とNullReferenceExceptionある、と私はそれをどのように修正すればよい?](http://stackoverflow.com/questions/4660142/what-is-a -nullreferenceexception-and-how-do-i-fix-it) –

+2

最初に行うことは、.NET命名規則に従うことを強くお勧めします。次に、 'Page_Load'メソッドでは、* fields *に値を代入していないことに注意してください。ローカル変数を宣言して値を代入しています。 –

+0

その 'quantitylabel.Text'コードを削除すれば、レンダリングされたページはどのように見えるでしょうか?それはid 'quantitylabel'のアイテムを持っていますか? 'Page_Load'イベントで' Log.Write( "quantitylabelがnull:{0}"、quantitylabel == null) 'のようなものをログに記録するとどうなりますか? –

答えて

0

DataList内のコントロールを使用して、使用したい場合は、ItemDataBoundを使用します。例えば

<asp:DataList ... OnItemDataBound="Item_Bound" runat="server"> 
</asp:DataList> 

void Item_Bound(Object sender, DataListItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListItemType.Item || 
     e.Item.ItemType == ListItemType.AlternatingItem) 
    { 
     Label lefthowmanylabel =(Label)e.Item.FindControl("Lefthowmanylabel"); 
     Label quantitylabel = (Label)e.Item.FindControl("quantitylabel"); 

     if (int.Parse(quantitylabel.Text) < 11) 
     { 
      lefthowmanylabel.Visible = true; 
     } 
     else 
     { 
     lefthowmanylabel.Visible = false; 
     } 
    } 
} 
関連する問題