【发布时间】:2015-04-08 18:03:59
【问题描述】:
我正在尝试使用组合框中的信息插入 Access 表记录。我正在使用 winform 和 C#。我已经简化了我的项目,只包括问题区域。我展示了带有 4 个控件(2 个按钮和 2 个组合框)的三种方法。第一种方法是连接到 Access 数据库,然后在第一个组合框中显示表和视图的列表。此方法还将调用最后一个方法 SelectName( ) 并用所选数据库中预定表中的字段内容填充第二个组合框。第二种方法 (buttonInsert_Click()) 是我的问题所在。我希望该方法将所选项目从组合框 1 插入到所选表之一中单击插入按钮时来自组合框2。我可以插入到所选表中的唯一内容是
System.Data.DataRowView
我的项目的 C# 部分如下。任何建议表示赞赏。谢谢。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DbApp
{
public partial class Form1 : Form
{
private char ch = '"';
private OleDbConnection dbConn;
private string sql = "";
public Form1()
{
InitializeComponent();
}
private void buttonConnect_Click(object sender, EventArgs e)
{
string connectionString = "";
string stringData = "";
openFileDialog1.Filter = "";
openFileDialog1.ShowDialog();
Text = openFileDialog1.FileName;
stringData = openFileDialog1.FileName;
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ch + Text + ch;
if (dbConn != null)
dbConn.Close();
dbConn = new OleDbConnection(connectionString);
dbConn.Open();
comboBox1.Items.Clear();
DataTable info = dbConn.GetSchema("Tables");
for (int x = 0; x < info.Rows.Count; ++x)
{
if ((info.Rows[x][3].ToString() == "TABLE") || (info.Rows[x][3].ToString() == "VIEW"))
{
comboBox1.Items.Add((object)info.Rows[x][2].ToString());
}
}
SelectName();
}
private void buttonInsert_Click(object sender, EventArgs e)
{
string name = this.comboBox2.SelectedItem.ToString();
try
{
dbConn = new OleDbConnection();
dbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
dbConn.Open();
sql = "INSERT INTO " + this.comboBox1.SelectedItem.ToString() + " (Names)" +
"Values (@name)";
OleDbCommand myCommand = new OleDbCommand(sql, dbConn);
myCommand.Parameters.Add("@name", OleDbType.VarChar).Value = name;
myCommand.ExecuteNonQuery();
myCommand.Connection.Close();
}
catch (Exception err)
{
MessageBox.Show("Error: " + err.Message.ToString());
}
}
private void SelectName()
{
string strCon = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + ch + openFileDialog1.FileName + ch;
try
{
using (dbConn = new OleDbConnection(strCon))
{
dbConn.Open();
sql = "SELECT Name FROM Names";
OleDbDataAdapter adapter = new OleDbDataAdapter(new OleDbCommand(sql, dbConn));
DataSet ds = new DataSet();
adapter.Fill(ds, "Names");
comboBox2.Items.Clear();
this.comboBox2.DataSource = ds.Tables["Names"];
this.comboBox2.DisplayMember = "Name";
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message.ToString());
}
}
}
}
【问题讨论】:
标签: c# winforms combobox ms-access-2010