更改数据库连接并更新datagridview

时间:2017-09-08 03:13:03

标签: c# database sqlite

我尝试在更改连接字符串数据源后显示数据库记录。这是我的代码:

m_dbConnection = new SQLiteConnection("Data Source=" + connFile + "; Version=3; FailIfMissing=True; Foreign Keys=True;");
getTable("SELECT * FROM tbl_programs WHERE int_is" +
    lastDisplayedBuild.ToString() +
    "=1 ORDER BY txt_programName;");

我的全局变量是:

private SQLiteConnection m_dbConnection;
private SQLiteDataAdapter sqliteDataAdapter = new SQLiteDataAdapter();
private DataTable dataTable = new DataTable();
private BindingSource bindingSource = null;

如何在datagridview中显示新记录?

1 个答案:

答案 0 :(得分:0)

使用此功能

public DataTable getData(string sqlCommand)
{
    DataTable dt = new DataTable();
    using (var con = new SQLiteConnection { ConnectionString = "your connection string" })
    {
       using (var command = new SQLiteCommand { Connection = con })
       {
           if (con.State == ConnectionState.Open)
               con.Close();

           con.Open();
           command.CommandText = sqlCommand;

           dt.Load(command.ExecuteReader());

       }
       return dt;
    }
 }


//Call to load your Data
public void loadData()
{
   this.DatagridView.DataSource = getData("Command string here");
}