2012-04-02 27 views
2

我有一个下拉列表框,如下所示。在某些情况下,在数据绑定事件中,我想删除其bitActive设置为0(不活动)的项目。我没有在selectCommand中放置WHERE bitAcive!= 0,因为我只想在某些条件下将其删除。有什么办法可以迭代项目并检查bitActive的值吗?如何根据ASP.net中的列名获取ListItem?

<tr> 
      <td width="30%" align="right">Location<span class="littlefont">*</span></td> 
      <td width="70%" align="left"> 
       <asp:DropDownList ID="ddlLocation" runat="server" 
        DataSourceID="SqlDSLocation" DataTextField="txtRefLocation_Name" 
        DataValueField="intRefLocation_ID" ondatabound="ddlLocation_DataBound"> 
       </asp:DropDownList> 
       <asp:SqlDataSource ID="SqlDSLocation" runat="server" 
        ConnectionString="<%$ ConnectionStrings:SPRConnectionString %>" 
        SelectCommand="SELECT DISTINCT [intRefLocation_ID], [txtRefLocation_Name], [location], [bitActive] FROM [tblRefLocation] ORDER BY [intRefLocation_ID]"> 
       </asp:SqlDataSource> 
      </td> 
     </tr> 

回答

1

在代码隐藏,你可以调用SQLDataSource.Select()方法:

System.Data.DataView dv = (System.Data.DataView)SqlDSLocation.Select(DataSourceSelectArguments.Empty); 

然后通过行迭代返回,发现谁设置为零的“bitActive”行,并从DropDownList(代码删除它们从上面链接的示例中入侵):

foreach(System.Data.DataRow row in dv.Table.Rows) 
{ 
    // This is approximate logic, tailor this to fit your actual data 
    if (row["bitActive"].ToString() == "False") 
    { 
     ddlLocation.Items.Remove(row["intRefLocation_ID"].ToString()); 
    } 
} 

请注意,这不会从SQL表中删除这些行。确保你不要在这之后再次绑定你的DropDownList--否则你刚刚移除的所有东西都会返回。

编辑:有关更高效优雅的解决方案,请参阅James Johnson's answer

+0

不要骂海报的答案之前过滤数据源,但这既不是解决问题的有效或优雅的方式... – 2012-04-02 18:31:09

+1

@JamesJohnson不,这听起来不像批评* = * +1)你的答案,它*非常优雅! – jadarnel27 2012-04-02 18:40:06

+1

我真的没有批评你,因为你坚持OP已经使用的实现。我只是指出有更有效的方法。我希望你不要把它当作你的轻微,因为我看到你发布了一些可靠的代码。 – 2012-04-02 18:50:13

1

而是在ItemDataBound事件删除项目的,为什么不结合它?:

var table = new DataTable("MyTable"); //assume it's populated 
if (table.Rows.Count > 0) 
{ 
    var results = table.AsEnumerable().Where(r => r.bitActive).AsDataView().ToTable(); 
    if (!results.HasErrors) 
    { 
     DropDownList1.DataSource = results; 
     DropDownList1.DataBind(); 
    }   
} 
相关问题