0

我想过滤数据网格视图中的数据。我想用下面的代码做到这一点:

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_events中有数据。

我究竟做错了什么?

4

2 回答 2

0

试试这个代码:

您正在使用添加行。首先转换为数据表,然后使用过滤并将数据表添加到 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;

编辑

 DataView view = new DataView();
            view = dt.DefaultView;
            view.RowFilter = "Type='1301'"
 dataGridView1.DataSource = view;
于 2013-04-11T06:40:36.670 回答
0

view.RowFilter = "类型='1301'";

view.RowStateFilter = DataViewRowState.CurrentRows;

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

// 数据视图内容。

Tbl_events.DataSource = DataView1;

Tbl_events.DataBind();

于 2013-04-11T07:43:58.370 回答