0

我想编写代码将 DataColumn 添加到 DataTable,但是当我保存 DataTable 时,它​​不包含新的 DataColumn。

它保存我添加的任何新 DataRows,但不保存 DataColumns。

有人可以告诉我我做错了什么吗?

public partial class Form1 : Form
{
    MyDatabase DB;
    DataTable Products;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        DB = new MyDatabase();
        DB.Open(@"C:\Users\Grant\Documents\Database.accdb");
        Products = DB.GetTable("Products");
        AddColumn();
        AddRow();
        DB.Save(Products);
    }

    private void AddColumn()
    {
        DataColumn Column = new DataColumn();
        Column.DataType = Type.GetType("System.String");
        Column.ColumnName = "TestColumn";
        Products.Columns.Add(Column);
    }

    private void AddRow()
    {
        DataRow Row;
        Row = Products.Rows.Add(1, "B", "C");
    }
}

class MyDatabase
{
    // The following program has to be installed on the computer
    // http://www.microsoft.com/downloads/en/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

    private String provider = "Microsoft.ACE.OLEDB.12.0";
    private String source;
    private OleDbConnection connection;
    private String connectionString;
    private DataSet dataSet = new DataSet();
    private OleDbDataAdapter adapter;
    private OleDbCommandBuilder commandBuilder;

    public String Provider
    {
        get { return provider; }
        set { provider = value; }
    }
    public String Source
    {
        get { return Source; }
        set { source = value; }
    }
    public void Open(String Filename)
    {
        connectionString = @"Provider=" + provider + @";Data Source=" + Filename;
        connection = new OleDbConnection(connectionString);
        connection.Open();
        adapter = new OleDbDataAdapter();
    }
    public void BuildStrings()
    {
        commandBuilder = new OleDbCommandBuilder(adapter);
        adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
        adapter.InsertCommand = commandBuilder.GetInsertCommand();
        adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
    }
    public DataTable GetTable(String TableName)
    {
        adapter.SelectCommand = new OleDbCommand("SELECT * From " + TableName, connection);
        BuildStrings();
        adapter.Fill(dataSet, TableName);
        return dataSet.Tables[TableName];
    }
    public void Save(DataTable Table)
    {
        adapter.Update(Table);
        adapter.Update(dataSet, "Products");
    }
}
4

1 回答 1

0

从另一个论坛得到答案。

您不能使用数据集或数据表将新列/字段添加到数据库表,您可能需要将“ALTER TABLE”与 ADO.NET 命令一起使用。检查以下链接

如何使用 SqlDataAdapter 和 DataTable 将新列插入到数据库表中?[^]

使用 ADO.NET 命令向 VB 中的 SQL 表添加列[^]

于 2013-09-15T19:26:32.713 回答