在转发器控件中获取选定的下拉列表值

时间:2011-05-19 02:25:20

标签: c# asp.net drop-down-menu

我在转发器控件中有一个dropdownlist,我正在尝试获取值,并且我得到“对象引用未设置为对象的实例”。我不知道还有什么可以尝试的。感谢

ASPX代码:

   <asp:Repeater ID="GeneralRepeater" runat="server" 
             OnItemDataBound="GeneralRepeater_OnItemDataBound" 
                onitemcommand="GeneralRepeater_ItemCommand">
            <HeaderTemplate></HeaderTemplate>
            <ItemTemplate>
            <tr>
             <td class="style2">
             </td>
              <td class="style2">
                 <asp:DropDownList ID="GeneralDDL"  AppendDataBoundItems="true"  DataTextField="DiagnosisCode" 
                  DataValueField="DiagnosisCode" runat="server" AutoPostBack="True" />
               </td>

            </tr>
            </ItemTemplate>
            <FooterTemplate></FooterTemplate>
            </asp:Repeater>
        </asp:Panel>

背后的代码:

protected void GeneralRepeater_OnItemDataBound(object sender,
                                               RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item ||
            e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList myDDL = (DropDownList)e.Item.FindControl("GeneralDDL");
            Diagnosis oDiagnosis = new Diagnosis();
            DataView dv = new DataView(oDiagnosis.GetDiagnosis());
            myDDL.DataSource = dv;
            myDDL.DataTextField = "DiagnosisCode";
            myDDL.DataValueField = "DiagnosisCode";
            myDDL.DataBind();

        }
    }

protected void cmdSave_Click(object sender, EventArgs e)
{
    string ProductSelected;
    string FeatureSelected;
    string SectionSelected;


    foreach(RepeaterItem dataItem in GeneralRepeater.Items)
    {
         ProductSelected = ((DropDownList)GeneralRepeater.FindControl("GeneralDDL")).SelectedItem.Text; //error Object reference not set to an instance of an object.
    }                   
}

我在保存所选值时遇到问题..

1 个答案:

答案 0 :(得分:9)

我在代码中找到的是循环遍历generalrepeater项目。您正在以dataItem的身份访问转发器项。我在这里尝试了这个代码,理想情况下你的代码应该说

foreach(RepeaterItem dataItem in GeneralRepeater.Items)        
{               
  ProductSelected = ((DropDownList)dataItem.FindControl("GeneralDDL")).SelectedItem.Text; //No error
}

而不是

foreach(RepeaterItem dataItem in GeneralRepeater.Items) 
{
   ProductSelected = ((DropDownList)GeneralRepeater.FindControl("GeneralDDL")).SelectedItem.Text; //error Object reference not set to an instance of an object.
}