2015-01-02 31 views
0

我已經創建了aspx頁面兩個下拉列表爲如何在頁面加載時在下拉列表中設置默認值 - 在asp.net c#中?

    <div class="row-form"> 
       <div class="span3"> 
        Line of Authority&nbsp;<span class="RequiredField">* </span>: 
       </div> 
       <div class="span3"> 
       <asp:DropDownList ID="drpLineOfAuthority" AutoPostBack="true" onselectedindexchanged="drpJurisdiction_SelectedIndexChanged" runat="server"></asp:DropDownList> 
       <!-- <tpLineOfAuthority:ctLineOfAuthority ID ="chkLineOfAuthority" runat="server" /> --> 
       </div> 
        <div class="clear"> 
        </div> 
       </div> 

       <div class="row-form"> 
       <div class="span3"> 
        State&nbsp;<span class="RequiredField">* </span>: 
       </div> 

       <div class="span3"> 
         <asp:DropDownList ID="drpJurisdiction" AutoPostBack="true"  onselectedindexchanged="drpJurisdiction_SelectedIndexChanged" runat="server"></asp:DropDownList> 
      </div> 

在aspx.cs文件作爲

   protected override void Page_Load(object sender, EventArgs e) 
       { 
       if (!IsPostBack) 
       { 
       if (urlAction != URLAction.update) 
       { 
        FillDropDown(); 
       } 
       } 
      } 

     private void FillDropDown() 
     { 
     JurisdictionBL jbl; 
     jbl = new JurisdictionBL(0); 
     DataSet ds = new DataSet(); 
     jbl.FetchAll(ds); 
     ... 
     ... 
     if (urlAction != URLAction.update) 
     { 
      drpJurisdiction.SelectedValue = "--Please select any state--"; 
      drpLineOfAuthority.SelectedValue = "--Please select LOA--"; 
     } 
    } 

注意FillDropDown()函數是填充值下拉列表中的項目,這些值檢索從數據庫。
現在的問題是上面的代碼是不設置默認值的下拉列表! 請幫助我!

+0

' - 請選擇任何狀態 - '&' - 請選擇LOA - '您的下拉選項是否值?這些應該是文字!顯示綁定您的下拉列表的數據。 –

+0

是先生它應該是默認值 – Nida

+0

使用drpJurisdiction.SelectedIndex = 0 – Bayeni

回答

1

作爲新行添加默認值嘗試這樣的retrived值,它會工作

drpJurisdiction.Items.Insert(0, new ListItem("--Please select any state--", "0")); 
0

嘗試探索AppendDataBoundItems屬性。

<asp:DropDownList ID="drpJurisdiction" runat="server" AppendDataBoundItems="true"> 
    <asp:ListItem Text="--Please select any state--" Value="" /> 
</asp:DropDownList> 

確保AppendDataBoundItems設置爲true,否則,當你在代碼綁定數據的背後,將被清除。

或者,

<asp:DropDownList runat="server" ID="drpJurisdiction" ondatabound="OndrpJurisdictionDataBound"></asp:DropDownList> 
在後面的代碼

然後:

protected void OndrpJurisdictionDataBound(object sender, EventArgs e) 
{ 
    drpJurisdiction.Items.Insert(0, new ListItem("--Please select any state--", "")); 
} 
+0

爲什麼你想改變OPs數據源和硬代碼默認代碼? –

+0

這不起作用.... – Nida

+0

@Nida,這可能是因爲AutoPostBack =「true」。但是,爲什麼不嘗試在線程中給出的替代方法。 – Nair

0

它,因爲從數據庫列表中不包含字符串「 - 請選擇任何state--」和「 - 請選擇LOA--「,請確保您在源數據表中具有默認值。

例如,如果數據表DT是有從數據庫中,你可以在運行時

DataRow DR = DT.NewRow(); 
    DR[0] = "--Please select LOA--"; 
    DT.Rows.InsertAt(DR, 0); 
+0

您是如何知道「數據庫中的列表不包含字符串」的? –

+0

可以在DropDownList或ComboBox中設置的值不能是其他初始化的列表。 – Dennis

相關問題