我剛剛意識到,你可能使用不同的數據源爲這兩個網格,但指向相同的數據庫,對不對?我的下面的例子爲這兩個網格使用相同的數據源。不過,我通過使某些列不可見而在詳細視圖與普通視圖之間進行了比較。也許這個策略可以解決你的問題?
我的第一個想法是嘗試實現SelectionChanged事件,或者如果不是這樣的話,SelectionChanging事件。在你看到的地方刷新一下。但我沒有最終這樣做。
我寫了一個小程序如下。只要它不是刪除就可以將編輯保存到磁盤上(我在按下按鈕時保存刪除編輯時遇到問題,它在刪除命令上給出了空指針異常)。它還會在關閉程序之前保存更改(以便任何刪除行也會保存)。我確實發現deleteOne和deleteTwo按鈕(分別從第一個或第二個網格中刪除)實際上會導致刪除發生在兩個網格中。所以你可能會使用radGridView1.Rows.Remove(row)或RemoveAt(i)命令,如果這在你的情況下可行的話?
另一種可能性是,如果刷新不起作用,則可以將DataSource設置爲null,然後在刪除該行後再將其設置爲數據源。這有點激烈,但如果它是唯一有效的東西?我正在討論兩個網格的數據源。
我的代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Telerik.WinControls;
using Telerik.WinControls.Data;
using Telerik.WinControls.UI;
namespace RadControlsWinFormsApp1
{
public partial class RadForm1 : Telerik.WinControls.UI.RadForm
{
public RadForm1()
{
InitializeComponent();
}
private void RadForm1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'testdbDataSet.Customers' table. You can move, or remove it, as needed.
this.customersTableAdapter.Fill(this.testdbDataSet.Customers);
radGridView1.Columns["Address"].IsVisible = false;
}
private void radGridView1_RowsChanged(object sender, Telerik.WinControls.UI.GridViewCollectionChangedEventArgs e)
{
// if removing don't update, because if my delete button is pressed this
// will otherwise cause all sorts of problems and freezes the grid
if (e.Action != NotifyCollectionChangedAction.Remove)
{
try
{
customersTableAdapter.Update(testdbDataSet);
}
catch (DBConcurrencyException ex)
{
// unable to save right now, don't worry about it
}
}
radGridView2.Refresh();
}
private void butDeleteOne_Click(object sender, EventArgs e)
{
bool haveRemoved = false;
for (int i = 0; i < radGridView1.Rows.Count && !haveRemoved; ++i)
{
GridViewRowInfo row = radGridView1.Rows[i];
if (row.IsSelected)
{
haveRemoved = true;
radGridView1.Rows.RemoveAt(i);
}
}
}
private void butDeleteTwo_Click(object sender, EventArgs e)
{
bool haveRemoved = false;
for (int i = 0; i < radGridView2.Rows.Count && !haveRemoved; ++i)
{
GridViewRowInfo row = radGridView2.Rows[i];
if (row.IsSelected)
{
haveRemoved = true;
radGridView2.Rows.RemoveAt(i);
}
}
}
private void radGridView2_RowsChanged(object sender, GridViewCollectionChangedEventArgs e)
{
// if removing don't update, because if my delete button is pressed this
// will otherwise cause all sorts of problems and freezes the grid
if (e.Action != NotifyCollectionChangedAction.Remove)
{
try
{
customersTableAdapter.Update(testdbDataSet);
}
catch (DBConcurrencyException ex)
{
// unable to save right now, don't worry about it
}
}
radGridView1.Refresh();
}
private void RadForm1_FormClosing(object sender, FormClosingEventArgs e)
{
// ensure all data is saved back into database on close
customersTableAdapter.Update(testdbDataSet);
}
//private void radGridView1_CellEndEdit(object sender, Telerik.WinControls.UI.GridViewCellEventArgs e)
//{
//}
}
}