private void button4_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection("Server=.;Database=gaunli;Trusted_Connection=SSPI");
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string xm = dataGridView1.Rows[i].Cells["id"].EditedFormattedValue.ToString();
string id = dataGridView1.Rows[i].Cells["name"].EditedFormattedValue.ToString();
string name = dataGridView1.Rows[i].Cells["age"].EditedFormattedValue.ToString();
string age = dataGridView1.Rows[i].Cells["address"].EditedFormattedValue.ToString();
string address = dataGridView1.Rows[i].Cells["phone"].EditedFormattedValue.ToString();
string str = "update Guanliyuan set name='" + id + "',age='" + name + "',address='" + age + "',phone='"+address+"' where id='" + xm + "'";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter { SelectCommand = new SqlCommand(str, conn) };
da.Fill(dt);
this.dataGridView1.DataSource = dt;
SqlCommandBuilder scb = new SqlCommandBuilder(da);
da.Update(dt);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
SqlDataAdapter da = new SqlDataAdapter { SelectCommand = new SqlCommand(str, conn) };
你的str是之前的update,所以没有结果
你可以再写一条
string str1 = "select * from Guanliyuan";
SqlDataAdapter da = new SqlDataAdapter { SelectCommand = new SqlCommand(str1, conn) };
try
{
SqlConnection conn = new SqlConnection("Server=.;Database=gaunli;Trusted_Connection=SSPI");
conn.Open();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
string xm = dataGridView1.Rows[i].Cells["id"].EditedFormattedValue.ToString();
string id = dataGridView1.Rows[i].Cells["name"].EditedFormattedValue.ToString();
string name = dataGridView1.Rows[i].Cells["age"].EditedFormattedValue.ToString();
string age = dataGridView1.Rows[i].Cells["address"].EditedFormattedValue.ToString();
string address = dataGridView1.Rows[i].Cells["phone"].EditedFormattedValue.ToString();
string str = "update Guanliyuan set name='" + id + "',age='" + name + "',address='" + age + "',phone='"+address+"' where id='" + xm + "'";
string str = "select * from Guanliyuan where id='" + xm + "'";
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter { SelectCommand = new SqlCommand(str, conn) };
da.Fill(dt);
dt.Rows[0]["name"] = id;
dt.Rows[0]["age"] = name;
....
da.Update(dt);
}
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
需要首先查询出记录,然后才能更新。