简体   繁体   English

SqlDataAdapter.Update或SqlCommandBuilder无法正常工作

[英]SqlDataAdapter.Update or SqlCommandBuilder not working

I have a form with a datagrid, which is populated wih data from a sqlserver database. 我有一个带有datagrid的表单,它使用sqlserver数据库中的数据进行填充。 The datagrid populates fine but I am having trouble posting back the changes made by the user, to the table in the sql database. 数据网格填充正常,但我无法将用户所做的更改发回到sql数据库中的表。 My forms code is as follows: 我的表单代码如下:

public partial class frmTimesheet : Form
{
    private DataTable tableTS = new DataTable();
    private SqlDataAdapter adapter = new SqlDataAdapter();
    private int currentTSID = 0;

    public frmTimesheet()
    {
        InitializeComponent();
    }

    private void frmTimesheet_Load(object sender, EventArgs e)
    {
        string strUser = cUser.currentUser;            
        cMyDate cD = new cMyDate(DateTime.Now.ToString());
        DateTime date = cD.GetDate();
        txtDate.Text = date.ToString();
        cboTSUser.DataSource = cUser.GetListOfUsers("active");
        cboTSUser.DisplayMember = "UserID";
        cboTSUser.Text = strUser;
        CheckForTimeSheet();
        PopulateTimeSheet();
    }

    private void CheckForTimeSheet()
    {
        string strUser = cboTSUser.Text;
        cMyDate cD = new cMyDate(txtDate.Text);
        DateTime date = cD.GetDate();
        int newTSID = cTimesheet.TimeSheetExists(strUser, date);
        if (newTSID != this.currentTSID)
        {
            tableTS.Clear();
            if (newTSID == 0)
            {
                MessageBox.Show("Create TimeSheet");
            }
            else
            {
                this.currentTSID = newTSID;
            }
        }
    }

    private void PopulateTimeSheet()
    {
        try
        {
            string sqlText = "SELECT EntryID, CaseNo, ChargeCode, StartTime, FinishTime, Units " +
                             "FROM tblTimesheetEntries " +
                             "WHERE TSID = " + this.currentTSID + ";";
            SqlConnection linkToDB = new SqlConnection(cConnectionString.BuildConnectionString());
            SqlCommand sqlCom = new SqlCommand(sqlText, linkToDB);
            SqlDataAdapter adapter = new SqlDataAdapter(sqlCom);
            adapter.SelectCommand = sqlCom;
            SqlCommandBuilder builder = new SqlCommandBuilder(adapter);
            adapter.Fill(tableTS);
            dataTimesheet.DataSource = tableTS;                
        }
        catch (Exception eX)
        {
            string eM = "Error Populating Timesheet";
            cError err = new cError(eX, eM);
            MessageBox.Show(eM + Environment.NewLine + eX.Message);
        }         
    }

    private void txtDate_Leave(object sender, EventArgs e)
    {
        CheckForTimeSheet();
        PopulateTimeSheet();            
    }

    private void cboTSUser_DropDownClosed(object sender, EventArgs e)
    {
        CheckForTimeSheet(); 
        PopulateTimeSheet();
    }

    private void dataTimesheet_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        try
        {   
            adapter.Update(tableTS);
        }
        catch (Exception eX)
        {
            string eM = "Error on frmTimesheet, dataTimesheet_CellValueChanged";
            cError err = new cError(eX, eM);
            MessageBox.Show(eM + Environment.NewLine + eX.Message);
        }
    }
}

No exception occurs, and when I step through the issue seems to be with the SqlCommandBuilder which does NOT build the INSERT / UPDATE / DELETE commands based on my gien SELECT command. 没有异常发生,当我逐步解决问题似乎是SqlCommandBuilder,它没有基于我的gien SELECT命令构建INSERT / UPDATE / DELETE命令。

Can anyone see what I am doing wrong? 谁能看到我做错了什么?

What am I missing? 我错过了什么?

You need to set the UpdateCommand instead of SelectCommand on update: 您需要在更新时设置UpdateCommand而不是SelectCommand

 SqlDataAdapter adapter = new SqlDataAdapter();
 SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
 adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;

The question is old, but the provided answer by@Anurag Ranjhan need to be corrected. 这个问题很古老,但@ Anurag Ranjhan提供的答案需要纠正。

You need not to write the line: 你不需要写行:

   adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;

and enough to write: 足以写:

   SqlDataAdapter adapter = new SqlDataAdapter();
   SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)
   //remove the next line
   //adapter.UpdateCommand = sqlBld.GetUpdateCommand() ;

The Sql update/insert/delete commands are auto generated based on this line Sql update / insert / delete命令是基于此行自动生成的

 SqlCommandBuilder sqlBld = new SqlCommandBuilder(adapter)

You can find the generated update sql by executing the line: 您可以通过执行以下行来找到生成的更新sql:

 sqlBld.GetUpdateCommand().CommandText;

See the example How To Update a SQL Server Database by Using the SqlDataAdapter Object in Visual C# .NET 请参阅如何在Visual C#.NET中使用SqlDataAdapter对象更新SQL Server数据库的示例

The problem said by OP can be checked by reviewing the Sql Statement sent by the client in SQl Server Profiler . 可以通过查看客户端在SQl Server Profiler发送的Sql语句来检查OP所述的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM