0

我需要将 Datagridview 中的数据插入 Sql Server 2008 中的数据库。但不工作。

“.Rows(i)”消息错误:

'不可调用的成员'System.Windows.Forms.DataGridView.Rows'不能像方法一样使用。'

代码 C#(Windows 窗体)

SqlConnection Conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
StringBuilder sb = new StringBuilder();
SqlTransaction tr;

private void testExcel_Load(object sender, EventArgs e)
{
    string appConn = ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
    Conn = new SqlConnection();
    if (Conn.State == ConnectionState.Open)
    {
        Conn.Close();

    }
    Conn.ConnectionString = appConn;
    Conn.Open();
}

private void button2_Click(object sender, EventArgs e)
{
    tr = Conn.BeginTransaction();

    sb.Remove(0, sb.Length);
    sb.Append("INSERT INTO tableAset (Id,AsId,AsRefid,Invid,TypeName)");
    sb.Append("VALUES (@Id,@AsId,@AsRefid,@Invid,@TypeName)");
    string sqlSave = sb.ToString();

    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {     
      cmd.CommandText = sqlSave;
      cmd.CommandType = CommandType.Text;
      cmd.Connection = Conn;
      cmd.Transaction = tr;
      cmd.Parameters.Clear();

      cmd.Parameters.Add("@Id", SqlDbType.Int).Value = dataGridView1.Rows(i).Cells(0).Value;
      cmd.Parameters.Add("@AsId", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(1).Value;
      cmd.Parameters.Add("@AsRefid", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(2).Value;
      cmd.Parameters.Add("@Invid", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(3).Value;
      cmd.Parameters.Add("@TypeName", SqlDbType.VarChar).Value = dataGridView1.Rows(i).Cells(4).Value;

      cmd.ExecuteNonQuery();
      tr.Commit();
      MessageBox.Show("It's Done!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
}

非常感谢您的宝贵时间。:)

4

3 回答 3

0

您应该使用rows[i]代替,单元格也是如此:

dataGridView1.Rows[i].Cells[0].Value

查看Rows 属性

于 2012-09-17T14:00:07.343 回答
0

只需用方括号替换圆括号

dataGridView1.Rows[i].Cells[0].Value;
于 2012-09-17T14:00:25.673 回答
0

我推荐使用 SqlBulkCopy。您可以轻松获取 DataTable 格式的 GridView 数据,您可以将 DataTable 传递给 SqlBulkCopy WriteToServer 您可以查看此示例。 https://www.aspsnippets.com/Articles/Using-SqlBulkCopy-to-insert-bulk-data-from-GridView-to-database-in-ASPNet.aspx

于 2019-09-09T02:03:57.243 回答