2016-01-21 47 views
0

我有一個主頁DropDownList和2個其他頁面。使其選擇打印報告的設置。
問題是 - 我在這些DropDownList s中使用DataSource s,但它們沒有空值。我應該在哪裏爲DropDownList添加一個新的空值以正確工作?
有我的代碼(在評論是,我需要添加的事情)我應該在哪裏爲DropDownList添加新的ListItem

protected void ddlMain_Load(object sender, EventArgs e) 
{ 
    switch (ddlMain.SelectedValue) 
    { 
     case "1": 
      dFirst.Visible = true; 
      dSecond.Visible = false; 
      break; 
     case "2": 
      dFirst.Visible = false; 
      dSecond.Visible = true; 
      break; 
} 

<div> 
<asp:DropDownList ID="ddlMain" runat="server" AutoPostBack="true" OnLoad="ddlMain_Load"> 
    <asp:ListItem Text="1" Value="1"></asp:ListItem> 
    <asp:ListItem Text="2 " Value="2"></asp:ListItem> 
</asp:DropDownList>    
</div> 

<div runat="server" id="dFirst" visible="false"> 
    <asp:DropDownList ID="ddlFirst" runat="server" DataSourceID="sdsFirst" 
     DataTextField="name" DataValueField="id" OnLoad="ddlFirst_Load"> 
    </asp:DropDownList> 
    <asp:SqlDataSource ID="sdsFirst" runat="server" 
     ConnectionString="<%$ ConnectionStrings:conStr %>"> 
    </asp:SqlDataSource> 
</div> 
//ddlFirst.Items.Add(new ListItem("--Select--", "-1")); 

我試圖OnLoad次要元素,OnLoad主要DropDownListPage_Load。它們不適合我,因爲新頁面ListItem在頁面首次加載時不會顯示,或在頁面刷新時添加超過1次。

+0

什麼是空值? – Imad

+0

對不起,我更新了我的問題!示例是註釋在代碼部分。 –

回答

1

在頁面加載中使用插入方法。

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

0是您想插入的位置。

+0

謝謝,但它只適用於一些Button_Click事件,但不適用於Page_Load –

0

optionlabel添加到您的下拉列表中,並指定文本「--Select--」。您的下拉列表現在應該具有所需的默認值。

+0

正確的DropDownList tegs?我不能,因爲那裏我可以放置ListItems。 –

+0

試着把它放在DDLFirst OnLoad後 –

+0

不幸的是,沒有幫助 –