更新DataTable中的单行

本文关键字:单行 DataTable 更新 | 更新日期: 2023-09-27 18:02:43

tl;博士:我想更新一个DataTable行,然后重新缓存整个DataTable(DataTable不仅仅是行(,这样我以后就可以在上使用它

我正在使用缓存来存储一个大的DataTable,我已经用基于MSSQL数据库的SqlAdapter填充了这个DataTable

我用这个缓存来获取DataTable,然后用它在网页中显示一个表,这里没有什么奇怪的。

但是这个DataTable包含一个用户列表,我希望能够编辑这些用户(在MSSQL数据库中编辑(,这很容易做到

问题是,在每次SQL更新之后,你必须重新缓存DataTable(否则它只会在数据库中更新,而不会在DataTable/网页中更新(,由于它非常大,这非常令人讨厌,并且使得非常简单的用户更新需要很长时间,因为它还必须使用SQL SELECT来获取所有帖子,然后重新缓存

正因为如此,我想在完成SQL更新后直接更新DataTable中的特定行,这样我就不必重新获取整个SQL表(SQL SELECT部分需要一段时间,因为它太大了(

到目前为止,我已经完成了

//We just updated our user, now we'll fetch that with SQL and put it in a new fresh DataTable(that contains just that one row) - since this is much faster than getting the whole table
//Then we'll use that DataTable containing one fresh row to update our old DataTable and re-cache it
DataTable newDataTable = getUserByID(userID); //Get our just edited DataTable row
DataTable cachedDataTable = getSetUserCache(); //Get our cached DataTable
DataRow oldRow = cachedDataTable.Select(string.Format("id = {0}", userID)).FirstOrDefault(); //Get the old row that contains the correct ID
string test = oldRow["status"].ToString(); //Contains the old and cached value before it got edited
oldRow = newDataTable.Rows[0]; //Update the old row with the new row
string test2 = oldRow["status"].ToString(); //Now it contains the new edited value
//Here I should update the cachedDataTable with the new row updated row
DataRow oldRowAfterUpdated = cachedDataTable.Select(string.Format("id = {0}", userID)).FirstOrDefault(); //Get the old row that now should be updated but isn't
string test3 = oldRowAfterUpdated["status"].ToString(); //Still contains the old and cached value before it got edited
success = updateUserCache(cachedDataTable); //Update the DataTable cache that we'll be using later on

我只看到关于如何更新行的帖子,但实际上如何用新行更新DataTable本身?

解决方案:

cachedDataTable.Select(string.Format("id = {0}", userID)).FirstOrDefault().ItemArray = newDataTable.Rows[0].ItemArray;

更新DataTable中的单行

我认为您可以使用DataRow:的ItemArray属性

void Main()
{
    DataTable tableOld = new DataTable();
    tableOld.Columns.Add("ID", typeof(int));
    tableOld.Columns.Add("Name", typeof(string));
    tableOld.Rows.Add(1, "1");
    tableOld.Rows.Add(2, "2");
    tableOld.Rows.Add(3, "3");
    DataTable tableNew = new DataTable();
    tableNew.Columns.Add("ID", typeof(int));
    tableNew.Columns.Add("Name", typeof(string));
    tableNew.Rows.Add(1, "1");
    tableNew.Rows.Add(2, "2");
    tableNew.Rows.Add(3, "33");
    tableOld.Rows[2].ItemArray = tableNew.Rows[2].ItemArray; //update specific row of tableOld with new values
    //tableOld.Dump();
}