【问题标题】:DataGridview duplication of data or not saving new rows to databaseDataGridview 重复数据或不将新行保存到数据库
【发布时间】:2014-03-04 00:04:23
【问题描述】:

我在使用 C# 的 windows 窗体中有 DataGridView

数据显示成功,更新也成功完成。

但问题在于插入。当我尝试使用迭代将多个数据插入数据库时​​,它将 13 次存储到数据库中,因为数据网格最初显示来自数据库的 13 条记录。我的意思是它将新行多次(datagridview 行数)存储到数据库中。

假设我想将两行保存到数据库中,但它将第一行存储到数据库中 13 次(datagridview 行的总数)。

请检查我在哪里做错了

注意:我想使用单个 datagridview 来显示、更新、插入和删除数据库中的数据。我有一个按钮,我想通过它开始将所有新行插入数据库。

我的代码在下面

string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;
using (SqlConnection sqlconn = new SqlConnection(connection))
{
    sqlconn.Open();                       
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow)
        {
            using (SqlCommand sqlcomm = sqlconn.CreateCommand())
            {
                 //sqlcomm.CommandText = "Insert into QF (profileID, UserNameLogInName, UserFullName,Email, forumtitle, subtitle, subjecttitle ,noreply, noview , qtags ,Question ,Questiondetails ,questionstatus, qdate,  Status ,todate) values(@status)";
                 sqlcomm.CommandText = "Insert into QF (UserNameLogInName,Status ) values(@UserNameLogInName,@status)";
                 try
                 {                                   
                     sqlcomm.Parameters.AddWithValue("UserNameLogInName", dataGridView1.CurrentRow.Cells["UserNameLogInName"].Value.ToString());
                     sqlcomm.Parameters.AddWithValue("Status", dataGridView1.CurrentRow.Cells["Status"].Value.ToString());
                     sqlcomm.ExecuteNonQuery();
                     //MessageBox.Show(dataGridView1.Rows[Convert.ToInt32(RecordIndexNumber.Text)].Cells[Convert.ToInt32(ColInexNum.Text)].Value.ToString());
                 }
                 catch (Exception ex)
                 {
                     btnInsert.Text = ex.Message.ToString();
                 }
             }
         }
     }
 }

我试过if (!row.IsNewRow),它只存储一行。没有它将多个不需要的时间存储到数据库中。

我也用过for (int i = 0; i < dataGridView1.Rows.Count - 1; i++),但同样的问题要么存储一次,要么存储多次。

我只是想插入用户在点击按钮时生成的新行。

【问题讨论】:

    标签: c# mysql sql database datagridview


    【解决方案1】:

    试试这个:

    sqlcomm.Parameters.AddWithValue("UserNameLogInName", row.Cells["UserNameLogInName"].Value.ToString());
    sqlcomm.Parameters.AddWithValue("Status", row.Cells["Status"].Value.ToString());
    

    【讨论】:

    • 它给出错误...对象引用未设置对象的实例
    • 问题是在foreach块中你总是调用同一行(dataGridView1.CurrentRow),你必须调用foeach语句的行(行)。
    • 为什么不去调试看看哪里出错了,一​​定要知道是哪一行抛出了异常。也可以尝试使用列的索引,如下所示:row.Cells[0]
    猜你喜欢
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2011-02-06
    相关资源
    最近更新 更多