从表数据库到gridview和对面

时间:2011-01-19 01:23:03

标签: c# asp.net

private void BindPrimaryGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    string query = "select * from Land";
    SqlConnection con = new SqlConnection(constr);
    SqlDataAdapter sda = new SqlDataAdapter(query, con);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gridview2.DataSource = dt;
    gridview2.DataBind();
}

从Land获取值并将它们传输到gridview2。我想做相反的事情。从gridview2.DataSource我想在Land中插入值。我怎样才能做到这一点?谢谢

2 个答案:

答案 0 :(得分:0)

http://www.vbforums.com/showthread.php?t=474895

//如果GridView1的DataSource是DataTable

DataTable dt =(DataTable)GridView1.DataSource;

//如果GridView1的DataSource是DataView

DataView dv =(DataView)GridView1.DataSource;

答案 1 :(得分:0)

假设表“Land”有3列:col1,col2,col3。请参阅以下代码。如有任何问题,请报告。

con.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
 {
    String insertData = "INSERT INTO Land (Col1,Col2,Col3) VALUES (@Col1,@Col2,@Col3)";
    SqlCommand cmd = new SqlCommand(insertData, con);
    cmd.Parameters.AddWithValue("@Col1", GridView1.Rows[i].Cells[0].Text);
    cmd.Parameters.AddWithValue("@Col2", GridView1.Rows[i].Cells[1].Text);
    cmd.Parameters.AddWithValue("@Col3", GridView1.Rows[i].Cells[2].Text);
    cmd.ExecuteNonQuery();
 }
con.Close();