在不使用dataset的情况下,如何使用C#使用sqlcommandbiulder更新数据库?

在不使用dataset的情况下,如何使用C#使用sqlcommandbiulder更新数据库?,c#,winforms,ado.net,sqlcommandbuilder,C#,Winforms,Ado.net,Sqlcommandbuilder,我有一个带有三个文本框的C#windows窗体应用程序,我想编辑文本框值并更新数据库(PhoneTable),或者使用sqlcommandbuilder使用编辑的文本框值更新数据库表。我尝试了下面的代码,但没有成功 SqlConnection phoneConnection; SqlCommand phoneCommand; SqlDataAdapter phoneAdapter; DataTable phoneTable; CurrencyManager phoneManager; //Sq

我有一个带有三个文本框的C#windows窗体应用程序,我想编辑文本框值并更新数据库(PhoneTable),或者使用sqlcommandbuilder使用编辑的文本框值更新数据库表。我尝试了下面的代码,但没有成功

SqlConnection phoneConnection;
SqlCommand phoneCommand;
SqlDataAdapter phoneAdapter;
DataTable phoneTable;
CurrencyManager phoneManager;

//SqlCommandBuilder phoneAdapterCommands;

private void frmPhoneDB_Load(object sender, EventArgs e)
{
    try
    {
        // connect to NWind database
        phoneConnection = new SqlConnection(
            "Data Source=DESKTOP-DICUCDS\\SQL2K14;Initial Catalog = PhoneDB; Persist Security Info = True; User ID = **********; Password = *********");

        //open the connection
        phoneConnection.Open();

        // establish command object
        phoneCommand = new SqlCommand("Select * from  phoneTable ORDER BY ContactName", phoneConnection);

        // establish data adapter/data table
        phoneAdapter = new SqlDataAdapter();
        phoneAdapter.SelectCommand = phoneCommand;

        phoneTable = new DataTable();
        phoneAdapter.Fill(phoneTable);

        //bind controls to data table

        txtID.DataBindings.Add("Text", phoneTable, "ContactID");
        txtName.DataBindings.Add("Text", phoneTable, "ContactName");
        txtNumber.DataBindings.Add("Text", phoneTable, "ContactNumber");

        // establish currency manager
        phoneManager = (CurrencyManager)this.BindingContext[phoneTable];

        SetState("View");
        this.Show();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error establishing Publishers table.",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        return;
    }
}

private void frmPhoneDB_FormClosing(object sender, FormClosingEventArgs e)
{
    try
    {
        // save the updated phone table sqlDbCommandBuilder

        SqlCommandBuilder phoneAdapterCommands = new SqlCommandBuilder(phoneAdapter);

        phoneAdapter.Update(phoneTable);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error saving database to file:\r\n" +
            ex.Message, "Save Error", MessageBoxButtons.OK,
            MessageBoxIcon.Error);
    }

    // close the connection PhoneDB.Close(); // dispose of the objects

    phoneConnection.Dispose();
    phoneCommand.Dispose();
    phoneAdapter.Dispose();
    phoneTable.Dispose();
}

欢迎来到Stackoverflow!请发一封邮件,以便我们能帮助你。你所发布的不是一个简单的例子。这是你的全部代码。