我需要在Datagridview中将数据插入到Sql Server 2008中的数据库中。但不起作用。C#的Windows窗体如何Datagridview数据库(SQL Server)?
“.Rows(我)” 消息错误:
'Non-invocable member 'System.Windows.Forms.DataGridView.Rows' cannot be used like a method.'
代码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);
}
}
非常感谢您的宝贵时间。 :)
试'.Rows [I]'和'细胞[n]的'(这是转换VB代码?) – Alex