从datatable更新数据库中的表

时间:2012-11-22 18:42:51

标签: c# ado.net

我从数据库表加载数据......

using (view_adapter = new SqlDataAdapter("select * from TVServiceProvider", connection_string))
        {
            using (dt = new DataTable())
            {
                view_adapter.Fill(dt);
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (dt.Columns[i].ColumnName.Substring(0, 2).Equals("id"))
                        dt.Columns[i].ReadOnly = false;
                }
                bs.DataSource = dt;
            }
        }

SqlDataAdapter view_adapterDataTable dt的位置。要将更改应用于数据库,我创建了方法

 void View_Adapter_Click(object sender, EventArgs e)
    {
        try
        {
            view_adapter.Update(dt);
            dt.AcceptChanges();
        }
        catch (Exception exc)
        {
            this.radLabelElement1.Text = exc.Message;
        }
    }

但是当我点击按钮时,我有一个例外。它需要更新命令。我应该在哪里和什么命令使用?

4 个答案:

答案 0 :(得分:2)

您必须为UpdateCommand创建DeleteCommandview_adapter

修改

代码必须如下所示:

SqlDataAdapter view_adapter = new SqlDataAdapter();
view_adapter .SelectCommand = new SqlCommand(queryString, connection);
view_adapter .UpdateCommand = new SqlCommand(updateCommadString, connection);
view_adapter .DeleteCommand = new SqlCommand(deleteCommadString, connection);

using (SqlConnection connection = new SqlConnection(connectionString))
    {
        view_adapter.Fill(dt);
        return dt;
    }

答案 1 :(得分:1)

嗯,你的代码中有些错误或不清楚 view_adapter 变量在using block语句中初始化 因此,当从using块退出时,view_adatpter将由框架处理并且在click事件中不可用。 (就像你从来没有打电话给新的来初始化它) 我怀疑你这里有另一个问题。 Using statement

此处的一部分,用于自动创建使用DataAdapter执行CRUD操作所需的UpdateCommand,InsertCommand和DeleteCommand,您可以使用 SqlCommandBuilder 。 (只有在select语句中使用一个表并且该表定义了主键时才可以这样做)

总结一切:

string queryString = "select * from TVServiceProvider";
view_adapter = new SqlDataAdapter(queryString, connection_string);
SqlCommandBuilder builder = new SqlCommandBuilder(view_adapter)
builder.GetUpdateCommand(); // Force the building of commands
view_adapter.Fill(dt);

然后您的点击事件应该按原样运行。

答案 2 :(得分:0)

此代码与您的代码无关,但可能对您有帮助,如果您看一看。我是从MSDN

得到的
public static SqlDataAdapter CreateCustomerAdapter(
    SqlConnection connection)
{
    SqlDataAdapter adapter = new SqlDataAdapter();

    // Create the SelectCommand.
    SqlCommand command = new SqlCommand("SELECT * FROM Customers " +
        "WHERE Country = @Country AND City = @City", connection);

    // Add the parameters for the SelectCommand.
    command.Parameters.Add("@Country", SqlDbType.NVarChar, 15);
    command.Parameters.Add("@City", SqlDbType.NVarChar, 15);

    adapter.SelectCommand = command;

    // Create the InsertCommand.
    command = new SqlCommand(
        "INSERT INTO Customers (CustomerID, CompanyName) " +
        "VALUES (@CustomerID, @CompanyName)", connection);

    // Add the parameters for the InsertCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");

    adapter.InsertCommand = command;

    // Create the UpdateCommand.
    command = new SqlCommand(
        "UPDATE Customers SET CustomerID = @CustomerID, CompanyName = @CompanyName " +
        "WHERE CustomerID = @oldCustomerID", connection);

    // Add the parameters for the UpdateCommand.
    command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    command.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, "CompanyName");
    SqlParameter parameter = command.Parameters.Add(
        "@oldCustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.UpdateCommand = command;

    // Create the DeleteCommand.
    command = new SqlCommand(
        "DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);

    // Add the parameters for the DeleteCommand.
    parameter = command.Parameters.Add(
        "@CustomerID", SqlDbType.NChar, 5, "CustomerID");
    parameter.SourceVersion = DataRowVersion.Original;

    adapter.DeleteCommand = command;

    return adapter;
}

答案 3 :(得分:0)

史蒂夫和哈姆雷特的建议对我有用的是以下内容。我有一次打嗝,因为我在进行视图适配器更新之前尝试对行和表进行接受更改。接受更改只需要在重新使用数据表在gridview或其他操作中显示之前保存对数据表的更改。

SqlDataAdapter viewAdapter = new SqlDataAdapter("Select * From Users", DBConn);
SqlCommandBuilder builder = new SqlCommandBuilder(viewAdapter);
viewAdapter.UpdateCommand = builder.GetUpdateCommand();


DataTable Users = new DataTable();
viewAdapter.Fill(Users);
foreach (DataRow user in Users.Rows)
{
    foreach (DataColumn c in Users.Columns)
    {
        Console.WriteLine(c.ColumnName);
        if (c.DataType != typeof(DateTime))
        {
            // Clean up empty space around field entries
            user[c.ColumnName] = user[c.ColumnName].ToString().Trim();
        }

    }
   // user.AcceptChanges(); 
   // Do not do an accept changes for either the table or the row before your ViewAdapter Update. 
   // It will appear as though you do not have changes to push.
}

// Users.AcceptChanges();
viewAdapter.Update(Users);