[英]DataView RowFilter doesn't filter the Rows on DataGridView
我具有此功能button_Search1_Click
來搜索與關鍵字匹配的注釋,然后在dataGridView_flaggedComments
顯示這些標記的注釋。
接下來,如果comboBox_stockIndex
有任何更改,我希望進行過濾,即在Tickers_Ticker_ID
為1
dataGridView_flaggedComments
過濾標記的注釋。 但是,當我這樣做時,所有注釋(無論是否標記)都屬於我的dataGridView_flaggedComments
上顯示的Tickers_Ticker_ID
的1
。 它應該只顯示Tickers_Ticker_ID
為1
的已標記注釋,而不是所有注釋。
我認為DataSource
出了點問題,但我無法弄清楚。 任何幫助將不勝感激! 謝謝!
(如果我確實錯過任何類似的問題,請指出。非常感謝!)
private void button_Search1_Click(object sender, EventArgs e)
{
commentCount = 0;
richTextBox_flaggedComments.Clear();
dataGridView_flaggedComments.Refresh();
DataTable flaggedcomments = new DataTable("flaggedcomments");
using (MySqlConnection sqlConn = new MySqlConnection(strProvider))
{
using (MySqlDataAdapter da = new MySqlDataAdapter(
"SELECT Comment_ID, Comments_Date, Author, Title, Comments_Comment, " +
" Tickers_Ticker_ID FROM comments ORDER BY Comments_Date ASC", sqlConn))
{
da.Fill(flaggedcomments);
}
}
StringBuilder sb = new StringBuilder();
string[] words = File.ReadAllLines(sourceDirTemp +
comboBox_crimeKeywords.SelectedItem.ToString() + ".txt");
var query = flaggedcomments.AsEnumerable().Where(r =>
words.Any(wordOrPhrase => Regex.IsMatch(r.Field<string>("Comments_Comment"),
@"\b" + Regex.Escape(wordOrPhrase) + @"\b", RegexOptions.IgnoreCase)));
dataGridView_flaggedComments.DataSource = query.AsDataView();
}
private void comboBox_stockIndex_SelectedIndexChanged(object sender, EventArgs e)
{
DataView dv = dataGridView_flaggedComments.DataSource as DataView;
if (dv == null)
throw new Exception("Bad Data Source type");
else
{
dv.RowFilter = string.Format("Tickers_Ticker_ID = '1'");
dataGridView_flaggedComments.DataSource = dv;
}
}
這樣的DataView
不會保存任何數據。
設置過濾器時,實際上是用新的過濾器(即RowFilter
替換LinqDataView
的原始過濾器(即Where
子句)。
您需要將它們串聯以創建雙重條件。
由於您的Where
子句使用了復雜的RegEx
我認為最簡單的方法是重新使用它,並為其添加新的簡單的'Tickers_Ticker_ID = ' + id
條件。
如果您不想重新應用原始過濾器,則可能希望將過濾后的行存儲在臨時表中。 在這里,我有一個DataSet DS,首先克隆了第一個表的結構,命名新表並將其添加到DataSet中。 在適當的時候,我從查詢中復制過濾的行:
設置臨時表,在其中設置其他數據庫內容:
DataSet DS; // if you don't already have one..
// put it at class level!
DS = new DataSet(); // ..create it
DataTable DT = DS.Tables[0].Clone(); // the temp table has the sdame structure
DT.TableName = "temp"; // is called by a name
DS.Tables.Add(DT); // and (optionally) added to the DataSet.
搜索時,將數據加載到臨時表中:
DS.Tables["temp"].Rows.Clear();
query.CopyToDataTable( DS.Tables["temp"], LoadOption.OverwriteChanges);
DGV.DataSource = DS.Tables["temp"];
現在,您可以在combo_filter_SelectedIndexChanged
事件中使用它:
string id = ddl_filter.Text;
if (id == "") DGV.DataSource = DS.Tables["temp"];
else
{
DataView dv = new DataView(DS.Tables["temp"])
dv.RowFilter = string.Format("id = " + id) ;
DGV.DataSource = dv;
}
您的過濾錯誤...請嘗試此...
dv.RowFilter = "Tickers_Ticker_ID = 1";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.