从数据集更新数据库

时间:2013-12-16 23:16:13

标签: asp.net database dataset

正如您在此代码中看到的那样,我在Button1_Click更新数据集ds,并且我想将对该数据集所做的更改更新到数据库。 如果我在Button1_Click写它是工作,但当我把完全相同的代码放在Unnamed1_Click它不工作,我不知道为什么!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class Discount : System.Web.UI.Page
{

    DataSet ds = new DataSet();

    public void Page_Load(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9"))
        {
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Items", con);  // יצירת dataAdapter
            da.Fill(ds);
            GridView2.DataSource = ds;
            GridView2.DataBind();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        int price;
        for (int i = 0; i < GridView2.Rows.Count; i++)
        {

            if (Convert.ToInt32(ds.Tables[0].Rows[i].ItemArray[4]) > Convert.ToInt32(minamount.Text))
            {
                price = Convert.ToInt32(ds.Tables[0].Rows[i][2]);
                price -= price * int.Parse(discountrate.Text) / 100;
                ds.Tables[0].Rows[i][2] = Convert.ToString(price);
            }
        }


        GridView2.DataSource = ds.Tables[0];
        GridView2.DataBind();

        //SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_");
        //con.Open();
        //SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
        //SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
        //tmpda.Update(ds);
    }

    protected void Unnamed1_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection("Data Source=Media.ruppin.ac.il;Initial Catalog=igroup9_test1; User ID=igroup9;Password=igroup9_86098"))
        {
            con.Open();
            SqlDataAdapter tmpda = new SqlDataAdapter("SELECT * FROM Items", con);
            SqlCommandBuilder builder = new SqlCommandBuilder(tmpda);
            tmpda.Update(ds);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您需要为SqlDataAdapter指定update命令。只需在commandBuilder instace之后插入以下代码:

tmpda.UpdateCommand = builder.GetUpdateCommand();