过滤dataGridView时,“对象引用未设置为对象的实例”

时间:2014-10-28 12:50:46

标签: c# datagridview filtering

我有这个搜索功能,为了标记匹配关键字列表的MySQL数据库中的注释,标记的注释将显示在dataGridView_flaggedComments上,然后填充comboBox_stockIndex所涉及的共享价格符号(例如BARC,LLOY,TSCO)。

private void button_Search1_Click(object sender, EventArgs e)
{
    commentCount = 0;
    dataGridView_flaggedComments.Refresh();
    DataTable flaggedcomments = new DataTable("flaggedcomments");
    using (MySqlConnection sqlConn = new MySqlConnection(strProvider))
    {
        using (MySqlDataAdapter da = new MySqlDataAdapter("SELECT Comment_ID, Comments_Date, Comments_Time, Author, Title, Comments_Comment, Tickers_Ticker_ID FROM comments ORDER BY Comments_Date ASC, Comments_Time 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();

    PopulateStockIndex();
}


private void PopulateStockIndex()
{
    comboBox_stockIndex.Items.Clear();
    comboBox_stockIndex.Items.Add("Choose to Filter");
    DataTable link_stockIndex = new DataTable("link_stockIndex");
    using (MySqlConnection sqlConn = new MySqlConnection(strProvider))
    {
        using (MySqlDataAdapter da = new MySqlDataAdapter("SELECT Ticker_ID, Symbol FROM tickers", sqlConn))
        {
            da.Fill(link_stockIndex);
        }
    }
    foreach (DataRow da in link_stockIndex.Rows)
    {
        for (int i = 0; i < dataGridView_flaggedComments.Rows.Count - 1; i++)
        {
            if (dataGridView_flaggedComments.Rows[i].Cells["Tickers_Ticker_ID"].Value.ToString() != "" && dataGridView_flaggedComments.Rows[i].Cells["Tickers_Ticker_ID"].Value.ToString() == da["Ticker_ID"].ToString())
            {
                if (!comboBox_stockIndex.Items.Contains(da[1].ToString()))
                {
                    comboBox_stockIndex.Items.Add(da[1].ToString());
                }
                comboBox_stockIndex.SelectedIndex = 0;
            }
        }
    }            
}

接下来,如果我从comboBox_stockIndex中选择一个符号,则应过滤dataGridView_flaggedComments以仅显示与所选符号相关的注释(一旦选择了符号,它将查找符号&# 39; s Tickers_TTicker_ID,然后按Tickers_Ticker_ID过滤)。但是下面的代码不起作用。有一个错误说&#34;对象引用未设置为对象的实例。&#34;这一行(dataGridView_flaggedComments.DataSource as DataTable).DefaultView.RowFilter = string.Format("Tickers_Ticker_ID = '{0}'", da["Ticker_ID"]);。我试图调试,但我不明白出了什么问题。

private void comboBox_stockIndex_SelectedIndexChanged(object sender, EventArgs e)
{
    DataTable link_stockIndex = new DataTable("link_stockIndex");
    using (MySqlConnection sqlConn = new MySqlConnection(strProvider))
    {
        using (MySqlDataAdapter da = new MySqlDataAdapter("SELECT Ticker_ID, Symbol FROM tickers", sqlConn))
        {
            da.Fill(link_stockIndex);
        }
    }
    foreach (DataRow da in link_stockIndex.Rows)
    {
        for (int i = 0; i < dataGridView_flaggedComments.Rows.Count - 1; i++)
        {
            if (dataGridView_flaggedComments.Rows[i].Cells["Tickers_Ticker_ID"].Value.ToString() != "" && comboBox_stockIndex.SelectedItem.ToString() == da["Symbol"].ToString())
            {
                (dataGridView_flaggedComments.DataSource as DataTable).DefaultView.RowFilter = string.Format("Tickers_Ticker_ID = '{0}'", da["Ticker_ID"]);
            }
        }
    }
}

我花了两天时间研究这个,SOF是我最后的选择。任何帮助将非常感谢!非常感谢你!

2 个答案:

答案 0 :(得分:3)

DataView不是DataTable

您可以将DataSoure设为DataView

dataGridView_flaggedComments.DataSource = query.AsDataView();

在此处,您将其投射为DataTable

(dataGridView_flaggedComments.DataSource as DataTable).DefaultView.RowFilter =...

所以,如果我很快理解你的问题,解决方案就是:

(dataGridView_flaggedComments.DataSource as DataView).RowFilter =...

下次将断点添加到出现此类错误的位置。查看您拥有的盒装类型以及您尝试拆箱的类型。 另外,我不建议像你一样使用as。最好这样做:

DataView dv = dataGridView_flaggedComments.DataSource as DataView;
if(dv == null)
    throw new Exception("Bad Data Source type");
else
{
    //use dv here
}

答案 1 :(得分:2)

从代码开始:dataGridView_flaggedComments.DataSource = query.AsDataView();

因此,当您尝试致电:(dataGridView_flaggedComments.DataSource as DataTable)时,您将获得null,因为DataSource不是DataTable而是DataView

看起来您应该使用类似(dataGridView_flaggedComments.DataSource as DataView).RowFilter的内容。