我是C#的新手。我正在尝试查询*.accdb
数据库,但响应中有0行,数据网格保持清晰。查询适用于MS Access。怎么了?
主要表单类
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
OleDbConnection database;
public Form1()
{
InitializeComponent();
}
private void filterButton_Click(object sender, EventArgs e)
{
MessageBox.Show(nameFilter.Text);
InitializeComponent();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\qwe.accdb;";
try
{
database = new OleDbConnection(connectionString);
database.Open();
string queryString = "SELECT id FROM table1";
loadDataGrid(queryString);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
public void loadDataGrid(string sqlQueryString) {
OleDbCommand comm = new OleDbCommand();
comm.CommandText = sqlQueryString;
comm.CommandType = CommandType.Text;
comm.Connection = database;
Int32 returnValue = comm.ExecuteNonQuery();
MessageBox.Show(returnValue.ToString());
OleDbCommand SQLQuery = new OleDbCommand();
DataTable data = null;
dataGridView1.DataSource = null;
SQLQuery.Connection = null;
OleDbDataAdapter dataAdapter = null;
dataGridView1.Columns.Clear(); // <-- clear columns
SQLQuery.CommandText = sqlQueryString;
SQLQuery.Connection = database;
data = new DataTable();
dataAdapter = new OleDbDataAdapter(SQLQuery);
dataAdapter.Fill(data);
dataGridView1.DataSource = data;
MessageBox.Show(data.ToString());
dataGridView1.AllowUserToAddRows = false; // <-- remove the null line
dataGridView1.ReadOnly = true; // <-- so the user cannot type
}
}
}
答案 0 :(得分:2)
为什么不出现以下内容:
private void filterButton_Click(object sender, EventArgs e)
{
dataGridView1.Columns.Clear();
MessageBox.Show(nameFilter.Text);
InitializeComponent();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\qwe.accdb;";
try
{
using (DataTable dt = new DataTable())
{
using (OleDbDataAdapter da = new OleDbDataAdapter(new SqlCommand("SELECT id FROM table1",new OleDbConnection(connectionString))))
{
da.Fill(dt);
MessageBox.Show(dt.Rows.Count.ToString());
dataGridView1.DataSource = dt;
dataGridView1.Update();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}