2013-11-26 83 views
-1

我正在使用ASP.NET,我有一個網格(radGrid)內的下拉列表。網格內DropDownList

我喜歡的事情是,當下拉列表出現時,我喜歡它默認爲 「請選擇」只有當它綁定到的字段是空白的。否則,我喜歡從DataSource中獲取價值。

我有以下代碼:

 <asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>        
    </asp:DropDownList> 

對於這裏的數據源代碼如下:

<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"   
     SelectCommand="Select Value from LookupValues where Category = 'EroGroup'"> 
    </asp:SqlDataSource> 

這裏是代碼隱藏代碼:

protected void ErogroupDropDown_DataBound(object sender, EventArgs e) 
    { 
     DropDownList list = sender as DropDownList; 

     if (list != null) 
     { 
      list.Items.Insert(0, new ListItem("Please Select", "")); 
     } 
    } 

當它會執行綁定,如果值爲空,則會顯示錯誤,指出找不到該值。

回答

0

爲此使用Grid PreRender事件。您可能需要將值分配給某個隱藏標籤,並在prerender方法中訪問它並將其分配給下拉菜單。

<ItemTemplate> 
    <asp:Label runat="server" ID="lblValue" Text='<%# Eval("YourValue")%>' Visible="false" /> 
    <asp:DropDownList ID="ddlEroGroup" runat="server" DataSourceID="EroGroupSource" DataTextField="Value" DataValueField="Value" AppendDataBoundItems="true" OnDataBound=" erogroupDropDown_DataBound" Text='<%# Bind("EroGroup") %>'>        
    </asp:DropDownList> 
<asp:SqlDataSource ID="EroGroupSource" runat="server" ConnectionString="<%$ ConnectionStrings:ISQL %>"   
     SelectCommand="Select Value from LookupValues where Category = 'EroGroup'"> 
    </asp:SqlDataSource> 
</ItemTemplate> 

在後面的代碼:

protected void GridView1_PreRender(object sender, EventArgs e) 
{ 
    for(int i=0;i<Gridview1.Rows.Count;i++) 
    { 
     Label lblValue = (Label)Gridview1.Row[i].FindControl('lblValue'); 
     DropdownList ddl = (DropdownList) Gridview1.Row[i].FindControl('ddlEroGroup'); 
     ddl.Items.Insert(0, new ListItem("Please Select", "")); 
     if(lblValue!=null && !String.IsNullOrEmpty(lblValue.Text)) 
      ddl.SelectedValue = lblValue.Text; 

    } 

} 
+0

謝謝,我想我的問題是,如果我做了綁定,如果該值是空白,如何將其默認爲請選擇? –

+0

如果有幫助,請參閱更新的答案 –

0

嘗試:

protected void ErogroupDropDown_DataBound(object sender, EventArgs e) 
    { 
     DropDownList list = sender as DropDownList; 

     if (list.Items.Count.equals(0)) 
     { 
      list.Items.Insert(0, new ListItem("Please Select", "")); 
     } 
    } 
相關問題