[英]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.