【问题标题】:How to replace / update DataRow in DataGridView如何替换/更新 DataGridView 中的 DataRow
【发布时间】:2012-08-25 15:36:56
【问题描述】:

我正在尝试更新 SQL 表中的单个记录。所以,我有该表的DataGridView 视图,当在表中选择了某些行并单击更新按钮时,将打开新的更新Form

主窗体将DataRow 行参数传递给新的Form,当更新结束时,行返回主窗体。 Main Form 中的代码示例大概是这样的:

private void btnUpdateUser_Click(object sender, EventArgs e)
{
  //Some code to extract DataRow
  FormUpdateUsers updateUser = new FormUpdateUsers(row, new Action<DataRow>(onUserUpdated));
  updateUser.Show();
}

当更新表单完成更新时,它会调用动作并将行返回给主表单,如下所示。

public partial class FormUpdateUsers : Form
{

private DataRow row;
private Action<DataRow> action;

public  FormUpdateUsers(DataRow row, Action<DataRow> action)
    {
        InitializeComponent();

        this.row = row;
        this.action = action;
    }

    private void btnConfirm_Click(object sender, EventArgs e)
    {
    //Some code for updatin a database
    action.Invoke(row);
    }
}

问题是,如何将返回的行晒到DataGridView 并替换过时的行?有什么建议吗?

private void onUserUpdated(DataRow row)
{
// Update DataGridView?
}

【问题讨论】:

  • 两个问题:如何获得传递给第二个表单的行,以及直接更新原始数据是否适合您?如果您只是将数据行传递给第二个表单,然后对其进行更新,则不需要将其传回 - 因为您正在处理同一个对象,所以数据表将自动更新。

标签: c# sql-server datagridview ado.net datarow


【解决方案1】:

你必须知道哪一行。 dgv(和数据行)中是否已有任何 id 列? 如果是这样,那么你可以这样做:

    private void onUserUpdated(DataRow row)
    {
        int idColumn = int.Parse(row["IdColumn"].ToString());
        foreach (DataGridViewRow DGVrow in dataGridView1.Rows)
        {
            if (idColumn == int.Parse(DGVrow.Cells["IdColumn"].Value.ToString()))
            {
                for (int i = 0; i < row.ItemArray.Length; i++)
                {
                    dataGridView1[i, DGVrow.Index].Value = row.ItemArray[i].ToString();
                }
            }
        }
    }

【讨论】:

  • 这行得通,谢谢!但是,有一些错误。声明一个值时,它没有 toString() 方法。最后,最后一个 NULL 行有问题,但我修复了这个问题,现在它可以完美运行了。再次感谢!
猜你喜欢
  • 2012-02-06
  • 1970-01-01
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
  • 2010-10-08
  • 2011-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多