我需要将 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);
}
}
非常感谢您的宝贵时间。:)