2010-04-01 74 views
0

我有下拉列表的一年即將動態。我已經填充下拉列表使用對象datasource.on插入列表視圖控件它工作正常。但是當我點擊編輯按鈕時,應該設置來自數據庫的dropdownlist值。 例如如果我有一個包含Year = 2006和Month =「Jan」 的行,那麼在點擊編輯按鈕時應該填寫這些下拉列表。在itemdatabound的列表視圖中設置下拉列表值

我已經在ItemDataBound中編寫代碼來設置dropdownlilst的值。但是當我使用findcontrol時,它將採用null,所以對象引用錯誤即將到來。所以請給我提供解決方案。

感謝

薩米爾

回答

0

我寫下面的代碼

保護無效ListView_Articles_ItemDataBound(對象發件人,ListViewItemEventArgs E) {

 if (e.Item.ItemType == ListViewItemType.DataItem) 
     { 
      if (cmd == "edit") 
      { 
       // Display the e-mail address in italics. 
       int month, year; 
       month = Convert.ToDateTime(DataBinder.Eval(((ListViewDataItem)e.Item).DataItem,"Created")).Month; 
       year = Convert.ToDateTime(DataBinder.Eval(((ListViewDataItem)e.Item).DataItem, "Created")).Year; 
       ListViewDataItem item = (ListViewDataItem)e.Item; 

       DropDownList ddlmonth = (DropDownList)e.Item.FindControl("ddlmonth"); 
       DropDownList ddlyear = (DropDownList)e.Item.FindControl("ddlyear"); 
       ListItem lstitem = ddlyear.Items.FindByValue(year.ToString()); 

//我發現那ddlyear是null它無法綁定數據。

if (ddlmonth != null) 
       { 
        foreach (ListItem monthitem in ddlmonth.Items) 
        { 
         if (int.Parse(monthitem.Value) == month) 
         { 
          ddlmonth.ClearSelection(); 
          monthitem.Selected = true; 
          return; 
         } 
        } 
       } 
       if (ddlyear != null) 
       { 
        foreach (ListItem yearitem in ddlyear.Items) 
        { 
         if (int.Parse(yearitem.Value) == year) 
         { 
          ddlyear.ClearSelection(); 
          yearitem.Selected = true; 
          return; 
         } 
        } 
       } 
      } 

     } 


    } 
+0

我已經解決了這個問題。刪除foreach循環,而不是寫ddlyear.selectedvalue = year,並且每個月也一樣。 – Samir 2010-04-02 10:48:16

2
protected void MyListView_ItemDataBound(object sender, ListViewItemEventArgs e) 
{ 
    if (e.Item.ItemType == ListViewItemType.DataItem) 
    { 
      DropDownList ddl = (DropDownList)e.Item.FindControl("nameOfDDLOnAspxPage"); 
      ddl.SelectValue = (however you are getting the year data for this row); 
    } 
}