Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从datatable从bounded datagridview更新插入数据_C#_Visual Studio 2013_Datagridview_.net 4.0 - Fatal编程技术网

C# 从datatable从bounded datagridview更新插入数据

C# 从datatable从bounded datagridview更新插入数据,c#,visual-studio-2013,datagridview,.net-4.0,C#,Visual Studio 2013,Datagridview,.net 4.0,我已从sql server数据库中的datatable绑定了datagridview 我需要知道如何在这个datagridview 如果有新的行,请直接将行添加到datagridview中,并将它们插入到数据库中 如果对以前绑定的数据进行了更新,则更新它 我搜索了一下,但我真的不知道怎么做 为什么我必须使用DataAdpterReader 为什么我必须使用数据集,它是一组数据表,而我已经有一个数据表 谢谢如果我理解正确,您只需要执行将重新填充“刷新”网格的相同查询,即OnClick-执行上面的代

我已从sql server数据库中的
datatable
绑定了
datagridview

我需要知道如何在这个
datagridview

如果有新的行,请直接将行添加到
datagridview
中,并将它们插入到数据库中 如果对以前绑定的数据进行了更新,则更新它

我搜索了一下,但我真的不知道怎么做

  • 为什么我必须使用
    DataAdpterReader

  • 为什么我必须使用
    数据集
    ,它是一组
    数据表
    ,而我已经有一个
    数据表


  • 谢谢

    如果我理解正确,您只需要执行将重新填充“刷新”网格的相同查询,即OnClick-执行上面的代码。我真的不明白你的if条款?如果有新的?新数据?要将其添加到数据库中吗?您可以将该功能添加到此OnClick事件中,以写入数据库中存在的任何内容,不管是否更改,这实际上取决于您显示的数据量,因此解决方案可能会有所不同。

    如果您希望DataGirdView中的行反映在数据库中,只需使用
    DataAdapter
    对象的方法即可

    简单地说,
    DataAdapter
    DataReader
    对象为您提供了一种简单高效的数据库读写方式。除此之外,它们还可以在不影响实际数据库表的情况下执行所有这些操作,这意味着在您这样说之前,所有内容都是未经更改的

    对于本例,假设我们有一个名为contacts的SQL表,其中有三列,即fname、mname和lname

    为了开始工作,我们需要一个函数,可以用来从“contacts”表中获取数据

    然后,可以通过执行以下操作将DGV绑定到存储在返回的dataset对象中的表

    DGV_Items.DataSource = GetData();
    
    在您的表单中加载事件

    现在我们已经完成了从数据库获取数据的方法的设置,我们现在设置了一个方法来处理我们现在拥有的所有数据

        protected void UpdateTable(DataSet ds)
        {
            SqlConnection conn = new SqlConnection(connString);
    
            // Insert, update and delete queries
            string updateQuery = "UPDATE contacts SET fname=@first,mname=@middle,lname=@last WHERE ID=@id";
            string deleteQuery = "DELETE FROM contacts WHERE ID=@id";
            string insertQuery = "INSERT INTO contacts VALUES(@first,@middle,@last)";
    
            // Create the parameters for the queries above
            SqlParameter[] insertParams = new SqlParameter[]
            {
                // the first parameter (e.g. @first) has to match with the declaration in the query
    
                // the second parameter (e.g.SqlDbType.NVarChar) is the data type of the actual column in the source table
    
                // the third paramter (e.g. 100) is the length of the data in the database table's column
    
                // the last parameter (e.g. "fname") is the DataPropertyName of the source column which is
                // basically the name of the database table column that the DGV column represents
    
                new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
                new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
                new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname")
            };
    
            SqlParameter[] updateParams = new SqlParameter[]
            {
                new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
                new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
                new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname"),
                new SqlParameter("@id", SqlDbType.Int, 100, "id")
            };
    
            SqlParameter[] DeleteParams = new SqlParameter[]
            {
                new SqlParameter("@id", SqlDbType.Int, 100, "id")
            };
    
            // Create the SqlCommand objects that will be used by the DataAdapter to modify the source table
            SqlCommand insertComm = new SqlCommand(insertQuery, conn);
            SqlCommand updateComm = new SqlCommand(updateQuery, conn);
            SqlCommand deleteComm = new SqlCommand(deleteQuery, conn);
    
            // Associate the parameters with the proper SqlCommand object
            insertComm.Parameters.AddRange(insertParams);
            updateComm.Parameters.AddRange(updateParams);
            deleteComm.Parameters.AddRange(DeleteParams);
    
            // Give the DataAdapter the commands it needs to be able to properly update your database table
            SqlDataAdapter dataAdapter = new SqlDataAdapter()
            {
                InsertCommand = insertComm,
                UpdateCommand = updateComm,
                DeleteCommand = deleteComm
            };
    
            // A DataTable and a DataSet are basically the same. Except the DataSet is a collection of DataTables
            // Here, you can see that we've accessed a specific DataTable in the DataSet.
    
            // Calling the Update method executes the proper command based on the modifications to the specified
            // DataTable object then commits these changes to the database
            dataAdapter.Update(ds.Tables["contacts"]);
        }
    
    上述方法将处理所有数据操作。它将根据对绑定到DGV的DataTable对象所做的更改进行操作。最后,您可以调用我们在update按钮的事件处理程序中创建的所有方法

        private void Btn_Update_Click(object sender, EventArgs e)
        {
            // Grab the DGV's data source which contains the information shown in the DGV
            DataSet ds = (DataSet)dgv_items.DataSource;
            // Have any updates to the said dataset committed to the database
            UpdateTable(ds);
            // rebind the DGV
            dgv_items.DataSource = GetData();
        }
    
    编辑 根据Crowcoder的建议,下面是一个更好的方法来编写我上面写的所有内容:

    /// <summary>
    /// A collection of methods for easy manipulation of the data in a given SQL table
    /// </summary>
    class DBOps
    {
        // The connection string contains parameters that dictate how we connect to the database
        private string connString = ConfigurationManager.ConnectionStrings["contactsConnectionString"].ConnectionString;
    
        // The table the instance of the class will be interacting with
        private string srcTable;
    
        // The SqlConnection Object that we will be using to connect to the database
        SqlConnection conn;
    
        // The DataAdapter object that we will be using to interact with our database
        SqlDataAdapter da;
    
        // The DataSet that we will be storing the data retrieved from the database
        DataSet ds;
    
        // The queries we would be using to manipulate and interact with the data in the database
        private string selectQuery;
        private string updateQuery;
        private string deleteQuery;
        private string insertQuery;
    
        // The collection of parameters for the queries above
        private SqlParameter[] insertParams;
        private SqlParameter[] updateParams;
        private SqlParameter[] DeleteParams;
    
        // The command objects that will be used by our data adapter when
        // interacting with the database
        private SqlCommand insertComm;
        private SqlCommand updateComm;
        private SqlCommand deleteComm;
    
        /// <summary>
        /// Initialize a new instance of the DBOps class
        /// </summary>
        /// <param name="tableName">The name of the table that the object will be interacting with</param>
        public DBOps(string tableName)
        {
            // Initialize the SqlConnection object
            conn = new SqlConnection(connString);
    
            // Initialize our collection of DataTables
            ds = new DataSet();
    
            srcTable = tableName;
    
            // initialize the query strings
            selectQuery = string.Format("SELECT * FROM {0}", srcTable);
            insertQuery = string.Format("INSERT INTO {0}(fname, mname, lnmae) VALUES(@first, @middle, @last", srcTable);
            updateQuery = string.Format("UPDATE {0} SET fname=@first, mname=@middle, lname=@last WHERE ID=@id", srcTable);
            deleteQuery = string.Format("DELETE FROM {0} WHERE ID=@id", srcTable);
    
            // Initialize the collection of parameters for each query above
            insertParams = new SqlParameter[]
            {
                // new SqlParameter(@paramName, paramDataType, paramValueLength, DGVDataPropertyName);
                new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
                new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
                new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname")
            };
    
            updateParams = new SqlParameter[]
            {
                new SqlParameter("@first", SqlDbType.NVarChar, 100, "fname"),
                new SqlParameter("@middle", SqlDbType.NVarChar, 100, "mname"),
                new SqlParameter("@last", SqlDbType.NVarChar, 100, "lname"),
                new SqlParameter("@id", SqlDbType.Int, 100, "id")
    
            };
    
            DeleteParams = new SqlParameter[]
            {
                new SqlParameter("@id", SqlDbType.Int, 100, "id")
            };
    
            // Initialize the SqlCommand objects that will be used by the DataAdapter to modify the source table
            insertComm = new SqlCommand(insertQuery, conn);
            updateComm = new SqlCommand(updateQuery, conn);
            deleteComm = new SqlCommand(deleteQuery, conn);
    
            // Associate the parameters with the proper SqlCommand object
            insertComm.Parameters.AddRange(insertParams);
            updateComm.Parameters.AddRange(updateParams);
            deleteComm.Parameters.AddRange(DeleteParams);
    
            // Give the DataAdapter the commands it needs to be able to properly update your database table
            da = new SqlDataAdapter()
            {
                InsertCommand = insertComm,
                UpdateCommand = updateComm,
                DeleteCommand = deleteComm
            };
        }
    
        /// <summary>
        /// Retrieve the data from the SQl table
        /// </summary>
        /// <returns></returns>
        public DataSet GetData()
        {
            DataSet ds = new DataSet();
    
            // Connect to the database and get the data from the "contacts" table
            using (conn)
            {
                conn.Open();
                using (SqlDataAdapter da = new SqlDataAdapter(selectQuery, conn))
                {
                    da.Fill(ds); // Add the rows from the "contacts" table to our dataset
                }
            }
    
            return ds;
        }
    
        /// <summary>
        /// Commit the changes present in the object's DataSet to the Database
        /// </summary>
        public void UpdateData(DataSet ds)
        {
            // Calling the Update method executes the proper command based on the modifications to the specified
            // DataTable object
            da.Update(ds.Tables[srcTable]);
        }
    
    更新按钮的单击事件处理程序中,可以通过调用UpdateData方法将所有更改提交给DGV的基础数据源

    总而言之:

    • DataAdapter
      DataReader
      对象为您提供了方法,使您能够以安全、高效和简单的方式与数据库交互
    • DataTable
      DataSet
      几乎相同。除了
      数据表
      只有一个表,而
      数据集
      数据表
      的集合。另一方面,它们中的每一个都有另一个没有的特定方法
    我提出了一个解决方案,我制作了一个方法来获取所有数据并将其添加到数据集中的DataTable中,如下面的示例所示

    public DATEaSet GetDATEa()
    {
        string connStr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
        string cmdStr = @"SELECT  SEQ,
                                           ID,
                                           DATE,
                                           Started,
                                           END,
                                           TYPE,
                                           ENTRANCE,
                                           OUTGOING
                                   FROM LOGING
                            WHERE SICK_ID=@ID;";
    
        SqlConnection conn = new SqlConnection(connStr);
        using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
        {
            try
            {
                conn.Open();
                cmd.CommandText = cmdStr;
                cmd.CommandType = CommandType.Text;
    
                ds = new DATEaSet();
                cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = Convert.ToInt32(TB_ID.Text);
                da = new SqlDATEaAdapter(cmd);
    
                da.Fill(ds, "DATEaTable1");
                MyDGV.Columns["MyDGV_RowNum"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["SEQ"].ColumnName;
                MyDGV.Columns["MyDGV_SessionID"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["ID"].ColumnName;
                MyDGV.Columns["MyDGV_DATEe"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["DATE"].ColumnName;
                MyDGV.Columns["MyDGV_StartTime"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["Started"].ColumnName;
                MyDGV.Columns["MyDGV_EndTime"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["END"].ColumnName;
                MyDGV.Columns["MyDGV_Type"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["TYPE"].ColumnName;
                MyDGV.Columns["MyDGV_CreatedBy"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["ENTRANCE"].ColumnName;
                MyDGV.Columns["MyDGV_EntryDATEe"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["OUTGOING"].ColumnName;
    
                return ds;
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.Substring(0, Math.Min(ex.Message.Length, 1024));
                MessageBox.Show(ErrorMsg);
                return null;
            }
        }
    }
    
    Form_Load
    事件中,我已将Datagridview的数据源设置为从上述方法返回的DS

    注意在某些情况下,必须明确设置
    DataMember

    MyDGV.DataSource = GetPatientSessions();
    MyDGV.DataMember = "DATEaTable1";
    
    现在,当用户编辑或将行添加到
    datagridview
    中,然后按保存按钮时,下面的方法将更新编辑数据并插入新输入的行

    private void BTN_Save_Click(object sender, EventArgs e)
    {
        using (SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(da))
        {
            try
            {
                da.Update(ds, "DATEaTable1");
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.Substring(0, Math.Min(ex.Message.Length, 1024));
                MessageBox.Show(ErrorMsg);
            }
        }
    }
    

    . 它使用
    SqlDataAdapter
    ,与数据表结合使用,可以跟踪并执行数据库中的CRUD。在看到
    SQLite…
    的地方,您可以将其与
    Sql…
    @Crowcoder一起使用。net4.5.2我正在使用
    。net4.0
    如果删除对SQLite的引用并添加以前的版本,它仍然可以工作。除此之外,它应该可以一直使用到.NET2.0,甚至更早。最坏的情况下,您可以引用代码,代码保持简单且有注释。我不建议每次更新适配器、数据集和命令/参数,并且
    AcceptChanges
    在您
    Update()
    时已被调用。啊,正确。我完全忘记了。另一方面,我过去常常把这样的东西分解,然后把它们放在一个叫做DatabaseOps的类中,我也建议OP也这样做。我应该编辑吗?谢谢你的反馈@Crowcoder:)@sam我又更新了代码。很抱歉。前缀为$的字符串值表示它是模板字符串,大括号之间的空格是放置变量的位置。以@符号为前缀的字符串表示它将被解释为是(签出)。另一方面,如果要将值传递给select查询,则必须执行以下操作:
    string selectQuery=$“select*FROM{tableName},其中ID=@ID;
    SqlCommand selectCommand=new SqlCommand(selectQuery);
    selectCommand.Parameters.AddWithValue(“id”,1);
    如果要将值传递给SqlCommand对象而不必指定数据类型,SqlParameter对象的构造函数有一个重载,其中只有参数的名称“@name”它的假定值是必需的,作为第二个参数的值可以是任何东西,从变量到从文本框中获取的东西。
    public DATEaSet GetDATEa()
    {
        string connStr = ConfigurationManager.ConnectionStrings["connstr"].ToString();
        string cmdStr = @"SELECT  SEQ,
                                           ID,
                                           DATE,
                                           Started,
                                           END,
                                           TYPE,
                                           ENTRANCE,
                                           OUTGOING
                                   FROM LOGING
                            WHERE SICK_ID=@ID;";
    
        SqlConnection conn = new SqlConnection(connStr);
        using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
        {
            try
            {
                conn.Open();
                cmd.CommandText = cmdStr;
                cmd.CommandType = CommandType.Text;
    
                ds = new DATEaSet();
                cmd.Parameters.Add(new SqlParameter("@ID", SqlDbType.Int)).Value = Convert.ToInt32(TB_ID.Text);
                da = new SqlDATEaAdapter(cmd);
    
                da.Fill(ds, "DATEaTable1");
                MyDGV.Columns["MyDGV_RowNum"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["SEQ"].ColumnName;
                MyDGV.Columns["MyDGV_SessionID"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["ID"].ColumnName;
                MyDGV.Columns["MyDGV_DATEe"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["DATE"].ColumnName;
                MyDGV.Columns["MyDGV_StartTime"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["Started"].ColumnName;
                MyDGV.Columns["MyDGV_EndTime"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["END"].ColumnName;
                MyDGV.Columns["MyDGV_Type"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["TYPE"].ColumnName;
                MyDGV.Columns["MyDGV_CreatedBy"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["ENTRANCE"].ColumnName;
                MyDGV.Columns["MyDGV_EntryDATEe"].DATEaPropertyName = ds.Tables["DATEaTable1"].Columns["OUTGOING"].ColumnName;
    
                return ds;
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.Substring(0, Math.Min(ex.Message.Length, 1024));
                MessageBox.Show(ErrorMsg);
                return null;
            }
        }
    }
    
    MyDGV.DataSource = GetPatientSessions();
    MyDGV.DataMember = "DATEaTable1";
    
    private void BTN_Save_Click(object sender, EventArgs e)
    {
        using (SqlCommandBuilder cmdbuilder = new SqlCommandBuilder(da))
        {
            try
            {
                da.Update(ds, "DATEaTable1");
            }
            catch (Exception ex)
            {
                string ErrorMsg = ex.Message.Substring(0, Math.Min(ex.Message.Length, 1024));
                MessageBox.Show(ErrorMsg);
            }
        }
    }