2016-04-30 21 views
0

後面的代碼中我正在嘗試從後面的代碼中找到InsertItemTemplate中的插入按鈕。基本上,我試圖讓這個按鈕的可見性錯誤,如果計數達到10或更多。我不斷收到空引用異常錯誤,所以我認爲它沒有找到按鈕。我已經粘貼代碼後面的代碼如下文件:試圖從ItemDataBound中的InsertItemTemplate中找到一個按鈕,位於

protected void externalLinksList_ItemDataBound(object sender, ListViewItemEventArgs e) 
{ 

     String connectionString = WebConfigurationManager.ConnectionStrings["UniString"].ConnectionString; 
     SqlConnection myConnection = new SqlConnection(connectionString); 

     myConnection.Open(); 

     String linkCountQuery = "SELECT COUNT(id) FROM links"; 

     SqlCommand linkCountQueryCommand = new SqlCommand(linkCountQuery, myConnection); 
     Int32 linkCountQueryCommandValue = (Int32)linkCountQueryCommand.ExecuteScalar(); 

     if (linkCountQueryCommandValue >= 10) 
     { 
      Button InsertButton = (Button)e.Item.FindControl("InsertButton") as Button; 
      InsertButton.Visible = false; 
      Label linkLimit = (Label)e.Item.FindControl("linkLimit") as Label; 
      linkLimit.Visible = true; 
      linkLimit.Text = "Up to 10 external links are permitted. Please delete links before adding any more."; 

     } 
     else 
     { 
      Button InsertButton = (Button)e.Item.FindControl("InsertButton"); 
     } 
    } 
+0

你有沒有嘗試在代碼中加入一些保護('if(InsertButton!= null){...}')?當您填充數據綁定控件時,所有項目都會觸發「ItemDataBound」事件,包括未處於插入模式的項目。對於這些項目,InsertButton將不會被找到。 (注意:如果你使用'...作爲按鈕',你不需要使用'(Button)...') – ConnorsFan

+0

@ConnorsFan在添加代碼後沒有更多的錯誤,但按鈕仍然可見並且它已經超過了我設置的限制 – Spiros

+0

你知道'linkCountQueryCommandValue'是否正確嗎?是否執行了「if」塊中的代碼或只有「else」塊? – ConnorsFan

回答

0

你已經在執行查詢一次生成的項目列表顯示和要綁定的ListView到數據源。此時,您可以檢查數據源的內容,以確定它包含的項目數。我不會重複那個查詢 - 返回到數據庫 - 顯示的每個單個項目再次獲得相同的編號。

有幾種方法可以做到這一點。最簡單的可能是

  • 當您執行初始查詢來填充ListView時,獲取該集合中的項目數。 (做到這一點,無論你正在爲ListView指定DataSource。)
  • 儲存於一個變量
  • externalLinksList_ItemDataBound檢查變量 - 項目列表中的原始計數 - 並用它來確定是否顯示或隱藏按鈕。

您也可以直接從externalLinksList_ItemDataBound檢查DataSource。 例如,如果數據源是任何類型的列表,你可以做

var listView = (ListView)sender; 
var dataSource = (IList)listView.DataSource; 
if(dataSource.Count >= 10) 
{ 
    //etc. 
} 

有可能是涉及對ListView本身設置屬性來禁用該按鈕更優雅的解決方案,但是這會做到這一點。

+0

項目計數是否在頁面加載完成?我仍然無法正常工作 – Spiros

相關問題