我試圖將DataGridView
鏈接到數據庫中的數據表。我想DataGridView
自動更新數據表(無需點擊「保存」或類似的東西)。在我看來,最好的辦法是處理RowValidating
事件。我一直在測試這段代碼,這是我的問題:假設我通過輸入DataGridView
中的最後一個空行來添加行#1(行#1,但不一定是第一行),並輸入一些錯誤的數據(空值或者應該有數字的文本等)。然後我按Enter鍵,出現一個新的空白行(第2行),沒有錯誤信息。在這個新的行中,我輸入了一些其他的數據,不對或不正確,然後再次按Enter鍵。現在我收到一條錯誤消息,第1行出現錯誤消息,但是焦點位於第2行,如果我嘗試編輯第1行,我又收到一條錯誤消息,焦點停留在第2行。我該如何處理?如何解決DataGridView.RowValidating問題
public Form1()
{
InitializeComponent();
sqlCeConnection.Open();
table = new DataTable();
sqlCeDataAdapter = new SqlCeDataAdapter("SELECT * FROM test", sqlCeConnection);
SqlCeCommandBuilder cBuilder = new SqlCeCommandBuilder(sqlCeDataAdapter);
sqlCeDataAdapter.Fill(table);
BindingSource bSource = new BindingSource();
bSource.DataSource = table;
dataGridView1.DataSource = bSource;
}
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
try
{
sqlCeDataAdapter.Update(table);
}
catch (Exception ex)
{
e.Cancel = true;
MessageBox.Show(ex.Message);
}
}
當您嘗試將焦點更改回第1行時,您會收到什麼錯誤消息? – 2010-10-04 05:04:06
無論行#1是什麼問題。我在我的帖子中解釋了這個錯誤,並且在我的代碼中的'MessageBox.Show(ex.Message);'顯示了它。問題不在於錯誤。問題在於,在添加第2行而不是第1行之後出現錯誤,即包含該錯誤的錯誤。 – Juan 2010-10-04 05:10:43