如何将数据从datagridview保存到数据库C# [英] How to save data from datagridview to database C#

查看:193
本文介绍了如何将数据从datagridview保存到数据库C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我添加了一个datagridview,用于动态地将数据存储到database.so我创建了foreach循环来获取行值。但似乎是一个错误。请帮帮我



我的尝试:



i added a datagridview for storing data dynamically in to database.so i created foreach loop for getting row values. but it seems an error. please help me

What I have tried:

 SqlDataAdapter da = new SqlDataAdapter("saleSave", con);// stored procedure for insertion
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            
           
            da.SelectCommand.Parameters.Add("@id", SqlDbType.Int).Value =id;
            da.SelectCommand.Parameters.Add("@invNo", SqlDbType.VarChar).Value = txt_Invoice.Text;
            int chklopp = Dgv_Invoice.Rows.Count;
            foreach (DataGridViewRow row in Dgv_Invoice.Rows)
            {
                if (chklopp!= 0)
                {
 da.SelectCommand.Parameters.Add("@item", SqlDbType.VarChar).Value = row.Cells["item"].Value.ToString();

da.SelectCommand.Parameters.Add("@description", SqlDbType.VarChar).Value = row.Cells["description"].Value.ToString();

da.SelectCommand.Parameters.Add("@unitPrice", SqlDbType.Float).Value = Convert.ToDouble(row.Cells["unit_price"].Value.ToString());

da.SelectCommand.Parameters.Add("@qty", SqlDbType.Int).Value = Convert.ToInt32(row.Cells["qty"].Value.ToString());

da.SelectCommand.Parameters.Add("@amount", SqlDbType.Float).Value = Convert.ToDouble(row.Cells["amount"].Value.ToString());

chklopp = chklopp - 1;
                }
            }

推荐答案

建议使用 BindingSource ,这个您的数据将自动保存的方式,请参见此处的示例: [ 如何:将数据绑定到Windows窗体DataGridView控件]

在此处查看CodeProject文章:详细的数据绑定教程 [ ^ ]
Using a BindingSource is the recommended way, this way your data will be saved automatically, see example here: [How to: Bind Data to the Windows Forms DataGridView Control]
And see CodeProject article here: A Detailed Data Binding Tutorial[^]


这篇关于如何将数据从datagridview保存到数据库C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆