鹿鸣湖
2018-11-15 05:15
采纳率: 33.3%
浏览 488

c#datagridview的数据存到数据库,但是dt没数据

图片说明

             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());
        }

    }
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • threenewbee 2018-11-15 05:26
    最佳回答

    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) };

    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题