我有一个方法可以将MS Access表的整个架构显示到datagridview控件中。我怎样才能在datagridview中只显示列名和数据类型架构列。我正在使用的方法如下。谢谢你的任何建议。
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
dbConn = new OleDbConnection();
dbCmd = new OleDbCommand();
DataTable data;
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
reader = dbCmd.ExecuteReader();
foreach (DataRow tableField in data.Rows)
{
foreach (DataColumn tableProperty in data.Columns)
{
dataGridView.DataSource = data;
}
}
this.txtRecords.Text = data.Rows.Count.ToString();
reader.Close();
dbConn.Close();
}
答案 0 :(得分:1)
以下是您修改的代码,可以根据需要使用OleDbDataAdapter:
private void ButtonFieldHelp_Click(object sender, EventArgs e)
{
char ch = '"';
var dbConn = new OleDbConnection();
var dbCmd = new OleDbCommand();
DataTable data = new DataTable();
OleDbDataReader reader;
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + this.stringData + ch;
dbConn.Open();
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT * FROM " + this.comboBox.SelectedItem.ToString();
//reader = dbCmd.ExecuteReader();
OleDbDataAdapter adapter = new OleDbDataAdapter(dbCmd);
adapter.Fill(data);
var dataTable = new DataTable();
dataTable.Columns.Add("ColumnName");
dataTable.Columns.Add("ColumnType");
foreach (DataColumn column in data.Columns)
{
dataTable.Rows.Add(column.ColumnName, column.DataType.ToString());
}
this.dataGridView1.DataSource = dataTable;
this.txtRecords.Text = data.Rows.Count.ToString();
dbConn.Close();
}