Populating DropDownList inside Repeater not working

谁说我不能喝 提交于 2019-11-28 12:37:35

Depsite the other answers on this question, the ItemDataBound event should not be used to bind control data, do that at the control level.

In your dropdownlist define the databinding event:

<asp:DropDownList runat="server" ID="ddlYourDDL"  OnDataBinding="ddlYourDDL_DataBinding">

Then implement the OnDataBinding event:

protected void ddlYourDDL_DataBinding(object sender, System.EventArgs e)
{
    DropDownList ddl = (DropDownList)(sender);
    for (int i = 1; i < 5; i++)
    {
         ddl.Items.Add(new ListItem(i.ToString(), i.ToString()));
    }

    // Now that the items are all there, set the selected property
    ddl.SelectedValue = Eval("selectedfieldname").ToString();
 }

You should try and do all your databinding at the control level instead of searching for things and having your grid have to know about what it contains. Each control can take care of itself ;) This way it is much easier to add and remove controls to your template and keep these changes isolated.

for(int i=1;i > 5;i++)

Should read ...

for(int i=1;i < 5 ;i++)
rick schott

In the .aspx Page:

<asp:Repeater runat="server" id="criteriaScore"   
              OnItemDataBound="criteriaScore_ItemDataBound">

In the Code-Behind:

protected void criteriaScore_ItemDataBound(object sender, RepeaterItemEventArgs e)
{

    // This event is raised for the header, the footer, separators, and items.

    // Execute the following logic for Items and Alternating Items.
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==   
        ListItemType.AlternatingItem) 
    {
         DropDownList ddl = (DropDownList)e.Item.FindControl("ddlRating");

         for(int i=0; i < 5; i++)
         {
            ddl.Items.Add(new ListItem(i.ToString(), i.ToString()));
         }
    }
 }  

private void criteriaScore_ItemDataBound(object source, RepeaterCommandEventArgs e)

Regardless of how the method is implemented (there are a few ways), the ItemDataBound event is not attached to the repeater in the markup.

Change: for(int i=1;i > 5;i++) To: for(int i=1;i < 5 ;i++)

Or:

    using System.Linq;

    ddl.DataSource = Enumerable.Range(1, 5);
    ddl.DataBind();
    ddl.SelectedValue = yourValue
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!