2010-04-01 76 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); 
    } 
}