将新项添加到datalist中的下拉列表

时间:2011-04-06 13:37:04

标签: asp.net drop-down-menu

我有一个Datalist,我正试图找到dropdown中的datalist,在ddl的第一个索引中添加文字我试图这样做但是这个出现了( object reference not set ....)

这是我的代码:

private  DropDownList DDLProduct;
 protected void Page_Load(object sender, EventArgs e)
    {


    }
 protected void DDlProduct_DataBound(object sender, EventArgs e)
    {
        DDLProduct.Items.Insert(0, new ListItem("Swithch Model", "0"));
    }
 protected void DLProduct_ItemDataBound(object sender, DataListItemEventArgs e)
    {


        DDLProduct = e.Item.FindControl("DDlProduct") as DropDownList;


    }

此致

6 个答案:

答案 0 :(得分:1)

你应该检查datalist的ItemDataBound事件,看看它是ListItemType.Item还是ListItemType.AlternatingItem类型,否则你是因为你在数据列表的标题上而点击空引用:

在C#中

if ((e.item.ItemType == ListItemType.Item) | (e.item.itemType == ListItemType.AlternatingItem))

在VB.net中:

if (e.Item.ItemType = ListItemType.Item) OR (e.Item.ItemType = ListItemType.AlternatingItem)

然后你想看看你是否能找到它:

在C#中

DropDownList d = (DropDownList) e.Item.FindControl("DDLProduct")

在vb.net中

Dim d as DropDownList = CType(e.Item.FindControl("DDLProduct"), DropDownList)

找到下拉列表框后,您可以执行以下操作:

d.Items.Insert(0, new ListItem("Switch Model", "0")); 

答案 1 :(得分:1)

也许你只需要AppendDataBoundItems: - )

答案 2 :(得分:0)

将代码放在if语句下面。

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {

     // Your code goes here to find the drop down list.      
}

由于页脚行的标题,您将获得空引用异常,因为此下拉列表不存在。

答案 3 :(得分:0)

试试这个。

  protected void DLProduct_ItemDataBound(Object sender, DataListItemEventArgs e)
  {

     if (e.Item.ItemType == ListItemType.Item || 
         e.Item.ItemType == ListItemType.AlternatingItem)
     {

        private  DropDownList DDLProduct = e.Item.FindControl("DDlProduct") as DropDownList;
        DDLProduct.Items.Insert(0, new ListItem("Swithch Model", "0"));

     }

  }

答案 4 :(得分:0)

使用它,它正在工作:

sQuery = "select * from tbl_Ticket_Msg where us_ID=0 and t_status='Open' order by T_id asc";
        ds3.Clear();
        ds3 = cl.getDataSet(sQuery);
        if (ds3.Tables[0].Rows.Count > 0)
        {
            DataList1.DataSource = ds3.Tables[0];
            DataList1.DataBind();
            lbltotal.Text = "Total Messages : " + ds3.Tables[0].Rows.Count.ToString();

            int row = Convert.ToInt32(ds3.Tables[0].Rows.Count);
            for (int i = 0; i < row; i++)
            {
                DropDownList ddl =  (DropDownList)DataList1.Items[i].FindControl("DropDownList1");
                ddl.DataSource = BindServicetoddl();
                ddl.DataTextField = "name1";
                ddl.DataValueField = "us_ID";
                ddl.DataBind();
            }
}

答案 5 :(得分:-1)

(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
相关问题