更新,编辑网格视图并将更改保存到数据库时出错 [英] Error while updating, editing the Grid view and saving the changes to Database

查看:83
本文介绍了更新,编辑网格视图并将更改保存到数据库时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个SaveButton,我试图添加一个新行,编辑行并保存更改。我能够编辑GridView中的现有行。问题是,当我尝试添加新行时,现有行将被修改。如果我使用`dt.Rows.Add(dr)`,则在编辑现有行并保存后会添加新行。



以下是我的代码:

I have a SaveButton through which I am trying to add a new row, edit the row and save the changes. I am able to edit the existing row in the GridView. The problem is when I try to add a new row the existing row is getting modified. If I use `dt.Rows.Add(dr)` then new row is getting added after editing the existing row and saving.

Below is my code:

private void btnSave_Click_1(object sender, EventArgs e)
    {
        int MyId;
        bool i = int.TryParse(txtID.Text, out MyId);
        da = new SqlDataAdapter();
        da.SelectCommand = new SqlCommand("select * from Measurement where ID = @ID",con);
        da.SelectCommand.Parameters.AddWithValue("@ID",MyId);
        SqlCommandBuilder cb = new SqlCommandBuilder(da);
        da.Fill(ds, "Measurement");

        if (String.IsNullOrEmpty(txtCellNo.Text.Trim()))
        {
            MessageBox.Show("Please enter Cell Number");
        }
        else
        {
            try
            {
                if (ds.Tables["Measurement"].Rows.Count < 1 )
                {
                    dt.Rows.Add();
                }
                else
                {
                    dr = ds.Tables["Measurement"].Rows[0];
                    dr["CellNumber"] = txtCellNo.Text.Trim();
                    dr["FirstName"] = txtFirstName.Text;
                    dr["LastName"] = txtLastName.Text;
                    dr["Shirt"] = txtShirt.Text;
                    dr["Pant"] = txtPant.Text;
                    dr["DueDate"] = txtDueDate.Text;
                    dr["Date"] = txtDate.Text;

                    cb.GetUpdateCommand();
                    da.Update(ds, "Measurement");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }





注意:我从Gridview获取了值使用Gridview Selection更改事件的文本框。



Note: I got the values from Gridview to Text Boxes using Gridview Selection changed event.

推荐答案

dr = ds.Tables["Measurement"].Rows[0];



你总是去第一排。



尝试使用


You are always going to the first row.

Try using

ds.Tables["Measurement"].Rows[ds.Tables["Measurement"].Rows.Count-1]

而不是


这篇关于更新,编辑网格视图并将更改保存到数据库时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆