0

我是 ASP.NET 的新手。单击“新建”以添加新记录时,我正在尝试将项目插入下拉列表。表单将从 ItemTemplate 切换到 InsertTemplate

错误:

“System.NullReferenceException:对象引用未设置为对象的实例。”

此代码在我的详细信息视图中。

    <ItemTemplate>
         <asp:Label ID="lblVendorName" 
        runat="Server" style="text-align:left; width:100%" 
        Text='<%# Eval("VendorName")%>' Width="70%"/>

    </ItemTemplate>    
    <InsertItemTemplate>
        <asp:DropDownList id="insertVendorName" datasourceid="VendorSqlDataSource"
            datatextfield="VendorName" DataValueField="VendorID"  
            OnSelectedIndexChanged="ddlVendor_SelectedIndexChanged" 
            runat="server" AutoPostBack="true"  />
        <asp:SqlDataSource ID="VendorSqlDataSource"  
        ConnectionString="<%$Connectionstrings:ConnectionString%>"
            SelectCommand="SELECT VendorID, VendorName 
                from MDF_Vendor"  runat="server">
        </asp:SqlDataSource>
    </InsertItemTemplate>

更新...下面是一组链接按钮。

<asp:TemplateField>  
    <ItemTemplate> 
        <asp:LinkButton ID="btnedit" runat="server" 
            CommandName="Edit" Text="Edit"/>  |   
        <asp:LinkButton ID="btnInsert" runat="Server" 
            Text="New" CommandName="New" 
            OnClick="LinkButton_Click"  />  |  
        <asp:LinkButton ID="btnDelete" 
            runat="server" 
            CommandName="Delete" Text="Delete" />      | 
    </ItemTemplate>  

    <InsertItemTemplate>
    <asp:LinkButton ID="btnInsert" runat="Server" 
        Text="Insert" CommandName="Insert"/>    
    <asp:LinkButton ID="btncancel" runat="server" 
        CommandName="Cancel" Text="Cancel"/> 
    </InsertItemTemplate>

    <EditItemTemplate>                                                 
        <asp:LinkButton ID="btnupdate" runat="server" 
            CommandName="Update" Text="Update" />                  
        <asp:LinkButton ID="btncancel" runat="server" 
            CommandName="Cancel" Text="Cancel"/>       
    </EditItemTemplate>
</asp:TemplateField> 

我尝试了@Aghislas 建议的以下代码(谢谢!)

protected void LinkButton_Click(object sender, EventArgs e)
{
    DropDownList ddlVendor = (DropDownList)DetailsView1.FindControl("insertVendorName"); 
    ddlVendor.Items.Insert(0, new ListItem("---Select---", "-1"));
} 

请帮忙。谢谢你。

4

1 回答 1

0

您可以尝试使用此代码

<asp:LinkButton id="LinkButton1" 
       Text="Click Me" 
       OnClick="LinkButton_Click" 
       runat="server"/>


 protected void LinkButton_Click(Object sender, EventArgs e) 
 {
      var ddlVendor =(DropDownList)DetailsView1.FindControl("insertVendorName");

      ddlVendor.Items.Insert(0, new ListItem("---Select---", "-1"));
 }

注意:您在 Click 委托中删除代码Page_Load并移入

于 2012-10-10T18:42:43.313 回答