绑定数据库表但不显示datagridview表中的数据

时间:2017-10-24 16:24:57

标签: c# datagridview

我正在尝试将DGV绑定到特定的表但不想让它显示表中的数据(仅用于插入查询)但我无法弄清楚如何在实际中完成此操作C#。这是我的代码(但同样,我不希望显示任何数据,只是列名,所以只需忽略选择查询,它就在那里解释我想要获取的内容)。

private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
   if (tabControl1.SelectedTab == tabControl1.TabPages["tabPage1"])
   {
       // set the data source and bind to childrens table
       this.dbcmd = this.dbconn.CreateCommand();

       this.dbcmd.CommandText = "SELECT first_name, last_name, birthday, email FROM children";

       this.dt = new DataTable();

       this.da = new SQLiteDataAdapter(this.dbcmd); // don't want this either I think

       this.da.Fill(this.dt); // this I know I do not want

       this.bindingSource = new BindingSource();

       this.bindingSource.DataSource = this.dt;

       dataGridViewChildren.DataSource = this.bindingSource;

   }
}

这有什么意义吗?如果我没有提供足够的信息,我很抱歉,如果需要更多信息,我会尝试提供更多信息。

感谢任何帮助,

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将DataTable的DefaultView的行过滤器属性设置为仅显示用户添加的行。

我这样做是通过在DataTable中添加一列来将所有查询的行设置为false。然后,任何时候从那里向DataTable添加一行就会设置为true。我将新列设置为不显示。

dt.Columns.Add(new DataColumn("UserAdded", typeof(bool)));
foreach (var row in dt.Rows.Cast<DataRow>())
    row["UserAdded"] = false;

bindingSource.DataSource = dt;
dataGridViewChildren.DataSource = bindingSource;
dataGridViewChildren.Columns.Cast<DataGridViewColumn>().Last().Visible = false;
dt.DefaultView.RowFilter = "UserAdded = true";

dt.TableNewRow += (s, e) =>
{
    e.Row["UserAdded"] = true;
};

单击插入按钮时,您可以获取用户添加的行...

var rows = dataGridViewChildren.Rows.Cast<DataGridViewRow>()
    .Where(r => !r.IsNewRow);