更新DATAGRID行以保存到SQL

时间:2016-05-09 12:56:22

标签: c# sql wpf datagrid

嗨大家好我想了解如何将行保存并编辑到db

 private void BudgetGrid_RowEditEnding(object sender, DataGridRowEditEndingEventArgs e)
        {
            SqlCommand gridcmd = new SqlCommand();
            SqlConnection rwConn = null;
            rwConn = new SqlConnection("server=localhost;" + "Trusted_Connection=yes;" + "database=Production; " + "connection timeout=30");
            gridcmd.Connection = rwConn;
            rwConn.Open();
            //gridcmd.CommandText = "SELECT Id, Name, Quantity, Rate, Time FROM Budget";
            gridcmd.CommandText = "UPDATE Budget SET Id = @id, Name = @Name, Quantity = @Qty, Rate = @Rte WHERE Time = @Time";

            SqlDataAdapter gridda = new SqlDataAdapter(gridcmd);

            string strId = "@id".ToString();
            int intID;
            bool bintID = Int32.TryParse(strId, out intID);


            string strName = "@Name".ToString();
            string strQty = "@Qty".ToString();
            int intQty;
            bool bintQty = Int32.TryParse(strQty, out intQty);
            string strRte = "@Rte".ToString();
            int intRte;
            bool bintRte = Int32.TryParse(strRte, out intRte);
            string strTime = "@Time".ToString();

            gridda.SelectCommand.Parameters.Add(new SqlParameter("@id", SqlDbType.Int));
            gridda.SelectCommand.Parameters["@id"].SqlValue = intID;
            gridda.SelectCommand.Parameters.Add(new SqlParameter("@Name", SqlDbType.VarChar));
            gridda.SelectCommand.Parameters["@Name"].SqlValue = strName;
            gridda.SelectCommand.Parameters.Add(new SqlParameter("@Qty", SqlDbType.Int));
            gridda.SelectCommand.Parameters["@Qty"].SqlValue = strQty;
            gridda.SelectCommand.Parameters.Add(new SqlParameter("@Rte", SqlDbType.Int));
            gridda.SelectCommand.Parameters["@Rte"].SqlValue = strRte;
            gridda.SelectCommand.Parameters.Add(new SqlParameter("@Time", SqlDbType.VarChar));
            gridda.SelectCommand.Parameters["@Time"].SqlValue = strTime;

            DataTable griddt = new DataTable("Budget");
            gridda.Fill(griddt);
            gridda.UpdateCommand = new SqlCommandBuilder(gridda).GetUpdateCommand();
            BudgetGrid.ItemsSource = griddt.DefaultView;
            gridda.Update(griddt);
            rwConn.Close();
        }

显示正常。我可以编辑它但是当我点击另一个标签时它没有更新它会回到原始数据。

我所经历的大部分代码都是过时的......或者不是我想要的。

所以这是数据库 enter image description here

这是应用enter image description here

所以基本上如果我点击Tab到下一行。在事件BudgetGrid_RowEditEnding下它应该更新数据库..但现在不是。

3 个答案:

答案 0 :(得分:1)

只需复制以下代码即可。我已经创造了你的所有东西并成功测试过。而不是第一种方式,我试图让你走得更受欢迎。因此,我花了很长时间才采用..

希望这能帮到你!

SqlDataAdapter da;
DataTable dt;

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        SqlConnection Conn = new SqlConnection();
        Conn.ConnectionString = yourConnectionString;
        Conn.Open();

        SqlCommand gridcomm = new SqlCommand();
        gridcomm.Connection = Conn;

        gridcomm.CommandText = "SELECT Id, Name, Quantity, Rate, Time FROM Budget";

        da = new SqlDataAdapter(gridcomm);

        SqlDataReader gridreader = gridcomm.ExecuteReader();
        while (gridreader.Read())
        {
        }
        gridreader.Close();

        dt= new DataTable("Budget");
        da.Fill(dt);

        dataGrid_Budget.ItemsSource = dt.DefaultView;

        Conn.Close();

    }

    private void dataGrid_Budget_RowEditEnding(object sender, System.Windows.Controls.DataGridRowEditEndingEventArgs e)
    {
        DataGridRow editedrow = e.Row;

        int row_index = (DataGrid)sender).ItemContainerGenerator.IndexFromContainer(editedrow);

        for (int k=0;k< 5;k++)
        {
            DataGridCell cell = GetCell(row_index, k);
            TextBlock tb = cell.Content as TextBlock;

            if (k==1)
            {
                dt.Rows[row_index][k] = tb.Text;
            }
            else if (k == 4)
            {
                if (tb.Text != "")
                {
                    dt.Rows[row_index][k] = Convert.ToDateTime(tb.Text);
                }
            }
            else
            {
                dt.Rows[row_index][k] = Convert.ToInt32(tb.Text);
            }
        }

        da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();

        da.Update(dt);
    }




    public DataGridCell GetCell(int row, int column)
    {
        DataGridRow rowContainer = GetRow(row);

        if (rowContainer != null)
        {
            DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);

            DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            if (cell == null)
            {
                dataGrid_Budget.ScrollIntoView(rowContainer, dataGrid_Budget.Columns[column]);
                cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
            }
            return cell;
        }
        return null;
    }

    public DataGridRow GetRow(int index)
    {
        DataGridRow row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
        if (row == null)
        {
            dataGrid_Budget.UpdateLayout();
            dataGrid_Budget.ScrollIntoView(dataGrid_Budget.Items[index]);
            row = (DataGridRow)dataGrid_Budget.ItemContainerGenerator.ContainerFromIndex(index);
        }
        return row;
    }

    public static T GetVisualChild<T>(Visual parent) where T : Visual
    {
        T child = default(T);
        int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
        for (int i = 0; i < numVisuals; i++)
        {
            Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
            child = v as T;
            if (child == null)
            {
                child = GetVisualChild<T>(v);
            }
            if (child != null)
            {
                break;
            }
        }
        return child;
    }

答案 1 :(得分:0)

您的SQL语法必须更正,

SqlCommand update_comm = new SqlCommand();
update_comm.Connection = Conn;
update_comm.CommandText = "UPDATE Budget SET id= @u_id, Name= @u_name  WHERE person= @psn";

var update_da = new SqlDataAdapter(update_comm);
update_da.SelectCommand.Parameters.Add(new SqlParameter("@u_id", SqlDbType.Int));
update_da.SelectCommand.Parameters["@u_id"].Value = yourintvalue;

update_da.SelectCommand.Parameters.Add(new SqlParameter("@u_name", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["@u_name"].Value = yourstringvalue;

update_da.SelectCommand.Parameters.Add(new SqlParameter("@psn", SqlDbType.NVarChar));
update_da.SelectCommand.Parameters["@psn"].Value = yourstringvalue;

var update_ds = new DataSet();
update_da.Fill(update_ds);

'UPDATE'应与'SET'一起使用。

如果您想使用已编辑的DataGrid行的值更新实际的SQL数据库,请尝试此操作。

da.UpdateCommand = new SqlCommandBuilder(da).GetUpdateCommand();

da.Update(griddt); 

答案 2 :(得分:-1)

  SqlConnection uniConn = null;
    SqlCommand cmd = null;
    SqlDataAdapter sda = null;
    DataTable dt = new DataTable();

    uniConn = new SqlConnection("server=localhost;" + "Trusted_Connection=yes;" + "database=Production; " + "connection timeout=30");
    cmd = new SqlCommand("UPDATE Budget(id, Name, Quantity, Rate, Time)", uniConn);
    uniConn.Open();

    sda = new SqlDataAdapter(cmd);
    sda.Fill(dt);
    BudgetGrid.ItemsSource = dt.DefaultView;
   uniConn.Close();

你是不是要关闭连接?