[英]Saving gridview updated data to SQL Server?
我可以將數據保存在gridView中,但是無法保存到數據源中。 可能會缺少代碼行,或者我缺少什么?
這是我的代碼:
public Marksheet(object val1)
{
InitializeComponent();
string connectionString = null;
SqlConnection conn;
connectionString = "Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=jms";
SqlDataAdapter sda6 = new SqlDataAdapter("SELECT * FROM grades WHERE class_code='" + val1 + "'", connectionString);
conn = new SqlConnection(connectionString);
DataTable dt5 = new System.Data.DataTable();
sda6.Fill(dt5);
gridControl1.DataSource = dt5;
}
private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
{
if (e.Button.ButtonType == DevExpress.XtraEditors.NavigatorButtonType.EndEdit)
{
if (MessageBox.Show("Do you want to commit changes to the current record?", "Confirm commit",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.No)
{
gridView1.CloseEditor();
gridView1.UpdateCurrentRow();
}
}
}
private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
//?? Could there be something I'm missing here? if yes, what could it be?
}
對網格控件進行任何更改時,更改都會反映在數據源中,在您的情況下就是DataTable
。 如果從邏輯上考慮,這似乎是正確的,因為網格控件已綁定到DataTable
,並且不知道如何填充DataTable
。
現在您可以看到使用DataAdapter
填充了DataTable
。 您需要調用DataAdapter.Update(dataTable)
方法將更改推送到數據庫。
如此處所述-將數據發布到連接的數據庫
@Aseem已建議最好的方法,您需要實現ADO.net綁定,才能使用DataAdapter
將更改提交回后端。 如果可以通過這種方式實現,請查看以下教程:
使用ADO.NET綁定到數據庫時,將控件綁定到包含來自數據庫的數據的DataTable。 當您通過網格控件更改數據(添加,刪除或修改記錄)時,更改將累積在DataTable中。 它們不會自動發布到基礎數據庫。 因此,您需要手動調用特定的方法來發布更改。
如果您使用的是自定義數據表,並且不願意實現這種綁定,則必須處理GridView.RowUpdated事件 ,然后可以回發然后在當前更新的行中進行的更改。
引用此: Xtragrid行更新的事件
例:
Private Sub gridView1_RowUpdated(ByVal sender As System.Object, ByVal e As DevExpress.XtraGrid.Views.Base.RowObjectEventArgs) Handles gridView1.RowUpdated
Dim val As Object
Dim row As DataRowView = CType(e.Row, DataRowView)
val = row(0)
End Sub
希望有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.