[英]C# Windows Form How to Datagridview to Database (Sql Server)?
I need Insert data in Datagridview to Database in Sql Server 2008. But don't work. 我需要将Datagridview中的数据插入Sql Server 2008中的数据库。但是不起作用。
".Rows(i)" Message Error: “ .Rows(i)”消息错误:
'Non-invocable member 'System.Windows.Forms.DataGridView.Rows' cannot be used like a method.' '不可使用的成员'System.Windows.Forms.DataGridView.Rows'不能像方法一样使用。
Code C# (Windows Form) 代码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);
}
}
Thank you very much for your time. 非常感谢您的宝贵时间。 :) :)
You should use rows[i] instead, the same goes for the Cells: 您应该改用rows [i] ,单元格也一样:
dataGridView1.Rows[i].Cells[0].Value
Take a look at the Rows property 看一下Rows属性
只需用方括号替换圆括号
dataGridView1.Rows[i].Cells[0].Value;
I recommend to use SqlBulkCopy.You can easily get the GridView data in DataTable format and you can pass the DataTable to SqlBulkCopy WriteToServer You can check this example. 我建议使用SqlBulkCopy。您可以轻松获取DataTable格式的GridView数据,并且可以将DataTable传递给SqlBulkCopy WriteToServer。 https://www.aspsnippets.com/Articles/Using-SqlBulkCopy-to-insert-bulk-data-from-GridView-to-database-in-ASPNet.aspx https://www.aspsnippets.com/Articles/Using-SqlBulkCopy-to-insert-bulk-data-from-GridView-to-database-in-ASPNet.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.