protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SqlConnection con = new SqlConnection("连接字符串"); string query = "SELECT * FROM 表名"; SqlCommand cmd = new SqlCommand(query, con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds); GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); } }
protected void Button1_Click(object sender, EventArgs e) { foreach (GridViewRow row in GridView1.Rows) { if (row.RowType == DataControlRowType.DataRow) { // 获取GridView单元格中的数据 string col1 = row.Cells[0].Text; string col2 = row.Cells[1].Text; // 将数据插入到另一个表中 SqlConnection con = new SqlConnection("连接字符串"); string query = "INSERT INTO 另一个表名 (列1, 列2) VALUES (@col1, @col2)"; SqlCommand cmd = new SqlCommand(query, con); cmd.Parameters.AddWithValue("@col1", col1); cmd.Parameters.AddWithValue("@col2", col2); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } }