C# Datagridview.datasource=null

C# Datagridview.datasource=null,c#,C#,我想在datagridview中过滤数据。 我希望使用以下代码执行此操作: DataView view = new DataView(); DataTable dt = new DataTable(); dt = Tbl_events.DataSource as DataTable; view = dt.DefaultView; view.RowFilter = "Type='1301'"; Tbl_events.DataSource = view; 这给了我一个空的datagridview

我想在datagridview中过滤数据。 我希望使用以下代码执行此操作:

DataView view = new DataView();
DataTable dt = new DataTable();
dt = Tbl_events.DataSource as DataTable;
view = dt.DefaultView; 
view.RowFilter = "Type='1301'";
Tbl_events.DataSource = view;
这给了我一个空的datagridview。 调试代码时,我在此行中看到:

dt = Tbl_events.DataSource as DataTable;
Tbl_events.DataSource = null;
但是datagridview Tbl_事件中有数据

我做错了什么?

请尝试以下代码:

您正在使用“添加行”。首先转换为datatable,然后使用筛选并将datatable添加到datagridview

     foreach (DataGridViewColumn c in dataGridView1.Columns)
            {
                dt.Columns.Add(new DataColumn(c.HeaderText.ToString()));
            }


        for (int row = 0; row < dataGridView1.Rows.Count; row++)
        {
            // create a new dt row to match up with the rows in the DGV
            DataRow dr = dt.NewRow();
            int column = 0;
            foreach (DataGridViewColumn c in dataGridView1.Columns)
            {
                //Sure you can see what this is doing.
                dr[c.HeaderText.ToString()] = dataGridView1.Rows[row].
                   Cells[column].Value;
                column++;
            }

            //now i add the row to the data table.
            dt.Rows.Add(dr);
        }


        dataGridView1.Rows.Clear();
 dt = dt.Select("Type='1301'").CopyToDataTable();
            dataGridView1.DataSource = dt;
view.RowFilter=“Type='1301'”

view.RowStateFilter=DataViewRowState.CurrentRows

//下面调用不同的方法来显示

//数据视图内容

Tbl_events.DataSource=DataView1


Tbl_events.DataBind()

什么是Tbl_事件这里..你能显示你最初设置
Tbl_事件的
DataSource
属性的代码吗?Tl_事件是一个datagridviewTbl_事件.Rows.Add(DataContainer.foutinformatie[0,lusteller],DataContainer.foutinformatie[1,lusteller],DataContainer.foutinformatie[2,lusteller],DataContainer.foutinformatie[3,lusteller],DataContainer.foutinformatie[4,lusteller]);当我尝试此操作时,我得到一个错误,对象引用未设置为对象的in实例。@user2261091,这将使用上面的编码,因为它会为我生成reslut。你的意思是什么?我如何将数据放置在表中?我使用此代码Tbl_events.Rows.Add执行此操作(DataContainer.foutinformatie[0,lusteller],DataContainer.foutinformatie[1,lusteller],DataContainer.foutinformatie[2,lusteller],DataContainer.foutinformatie[3,lusteller],DataContainer.foutinformatie[4,lusteller]);@user2261091 DataContainer,lusteller这意味着什么?Tbl_事件无法识别数据绑定();我必须为其添加dll吗?
 DataView view = new DataView();
            view = dt.DefaultView;
            view.RowFilter = "Type='1301'"
 dataGridView1.DataSource = view;