2013-05-15 55 views
0

我有一個包含4列的表。我希望能夠做的是根據多個DropDownList的選擇過濾這個數據表。DropDownList過濾數據表

如何刪除不包含選擇的行?我用SQL來填充數據表,但我不想調用SQL來過濾數據表?

我的繼承人,我怎麼添加數據表和代碼填充dropdownlists

private DataTable LoadDataTable() 
{ 
    //conn.Open(); 
    DataTable dt = new DataTable(); 
    SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM DataTest", conn); 

    adapter.Fill(dt); 
    conn.Close(); 
    return dt;           
} 

public void PopulateDDL() 
{ 
    SqlCommand cmd = new SqlCommand("SELECT DISTINCT Column1 FROM DataTest", conn); 
    cmd.Connection.Open(); 

    SqlDataReader ddlValues; 
    ddlValues = cmd.ExecuteReader(); 

    DropDownList1.DataSource = ddlValues; 
    DropDownList1.DataValueField = "Column1"; 
    DropDownList1.DataTextField = "Column1"; 
    DropDownList1.DataBind(); 

    cmd.Connection.Close();    
} 

無論如何,我能去嗎?

+0

選擇這行你所談論的刪除? –

+0

不包含下拉列表文本的行。因此,例如在下拉列表中選擇「TV」,我希望所有不包含「TV」的行都被刪除 – BlahWoo

回答

0

好了,你可以嘗試

// Presuming the DataTable has a column named List. 
string expression; 
expression = "List != TV"; 
DataRow[] foundRows; 

// Use the Select method to find all rows matching the filter. 
foundRows = table.Select(expression); 
0

如果要基於Multidropdown中的多個值選擇過濾數據表,可以使用以下代碼實現此目的。讓我們假設你multidropdown包含asp:CheckboxList ID爲chkMultiSelection

讓我們說你有System DataTable dt所有的數據和需要過濾器的基礎上MultiDropDownlist

var dataSet = new DataSet(); 
var filterDataTable = new DataTable(); 
//get all the selection of MultiDropDown and seperated them by comas.. 
string selectedValues = string.Join(", ", chkMultiSelection.Items.Cast<ListItem>().Where(x => x.Selected).Select(x => x.Text)); 

//convert your multiselection to array 
string[] multiValues = selectedValues.Split(','); 

//iterate through them and filter the data based on selection. That will filter the rows which don't contain the selection 
foreach (string s in multiValues) 
{ 
    IEnumerable<DataRow> datarow = default(IEnumerable<DataRow>); 
    datarow = dt.AsEnumerable().Where(x => x.Field<string>("ColumnName") == s.Trim()); 
    if (datarow.Count() > 0) 
    { 
     filterDataTable = datarow.CopyToDataTable(); 

     //use dataset and store each filter data 
     dataSet.Tables.Add(filterDataTable); 

    } 
}