dataGrid更新数据

本文介绍了一个使用C# WinForms实现的简单应用程序,该程序通过SqlConnection连接到本地SQL Server数据库,并使用SqlDataAdapter填充数据网格。此外,还实现了更新、插入和删除数据库记录的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace WindowsApplication1
{
 /// <summary>
 /// Form1 的摘要说明。
 /// </summary>
 public class Form1 : System.Windows.Forms.Form
 {
  private DataSet myDs;
  private SqlDataAdapter myDa;

  private System.Windows.Forms.DataGrid dataGrid1;
  private System.Windows.Forms.Button updt;
  private System.Windows.Forms.Button conndb;
  /// <summary>
  /// 必需的设计器变量。
  /// </summary>
  private System.ComponentModel.Container components = null;

  public Form1()
  {
   //
   // Windows 窗体设计器支持所必需的
   //
   InitializeComponent();
   //
   // TODO: 在 InitializeComponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void Dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.Dispose();
    }
   }
   base.Dispose( disposing );
  }

  #region Windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {
   this.updt = new System.Windows.Forms.Button();
   this.dataGrid1 = new System.Windows.Forms.DataGrid();
   this.conndb = new System.Windows.Forms.Button();
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
   this.SuspendLayout();
   //
   // updt
   //
   this.updt.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
   this.updt.Location = new System.Drawing.Point(344, 328);
   this.updt.Name = "updt";
   this.updt.Size = new System.Drawing.Size(200, 23);
   this.updt.TabIndex = 0;
   this.updt.Text = "Update to DataBase";
   this.updt.Click += new System.EventHandler(this.updt_Click);
   //
   // dataGrid1
   //
   this.dataGrid1.DataMember = "";
   this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
   this.dataGrid1.Location = new System.Drawing.Point(0, 0);
   this.dataGrid1.Name = "dataGrid1";
   this.dataGrid1.Size = new System.Drawing.Size(590, 312);
   this.dataGrid1.TabIndex = 1;
   //
   // conndb
   //
   this.conndb.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
   this.conndb.Location = new System.Drawing.Point(88, 328);
   this.conndb.Name = "conndb";
   this.conndb.Size = new System.Drawing.Size(168, 23);
   this.conndb.TabIndex = 2;
   this.conndb.Text = "Connection DataBase";
   this.conndb.Click += new System.EventHandler(this.conndb_Click);
   //
   // Form1
   //
   this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
   this.ClientSize = new System.Drawing.Size(592, 366);
   this.Controls.Add(this.conndb);
   this.Controls.Add(this.dataGrid1);
   this.Controls.Add(this.updt);
   this.Name = "Form1";
   this.Text = "Form1";
   ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
   this.ResumeLayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main()
  {
   Application.Run(new Form1());
  }

  private void updt_Click(object sender, System.EventArgs e)
  {
   try
   {
    SqlCommandBuilder cb = new SqlCommandBuilder();
    cb.DataAdapter = myDa;
    myDa.UpdateCommand = cb.GetUpdateCommand();
    myDa.DeleteCommand = cb.GetDeleteCommand();
    myDa.InsertCommand = cb.GetInsertCommand();
   
    myDa.Update(myDs.Tables["tab"]); 
    MessageBox.Show("Database updated!");
   }
   catch (Exception eupdt)
   {
    MessageBox.Show("没有更新成功,具体原因是:/n"+eupdt.Message);
   }
  }

  private void conndb_Click(object sender, System.EventArgs e)
  {
   SqlConnection conn= new SqlConnection();
   string connstr = "initial catalog = Northwind; data source = 127.0.0.1; uid= sa; pwd=";
   conn.ConnectionString = connstr;
   try
   {

    conn.Open();
    SqlCommand cmd= new SqlCommand();
    cmd.CommandText = "select * from customers";
    cmd.Connection = conn;
    myDa = new SqlDataAdapter();
    myDa.SelectCommand = cmd;
    myDs = new DataSet();

    myDa.Fill(myDs,"tab");
    dataGrid1.DataSource = myDs;
    dataGrid1.DataMember="tab";
    //dataGrid1.DataBind();  //去掉即可,

   }
   catch ( Exception econn)
   {
    MessageBox.Show("数据库连接错误(0)",econn.Message);
   }
   finally
   {
    conn.Close(); 
   }  
  }
 }
}

### NUI DataGrid 通过 Ajax 更新数据的方法 NUI DataGrid 是一个功能强大的表格控件,支持通过 Ajax 动态更新数据。以下是一个完整的示例,展示如何使用 DataGrid 并通过 Ajax 更新数据。 #### 示例代码 以下是一个基于引用[^1]和[^2]的完整实现: ```html <div id="datagrid1" dataField="expenses" class="nui-datagrid" style="width: 800px; height: 360px;" allowResize="true" url="com.primeton.train.expense.expenseQuery.biz.ext" sizeList="[20,30,50,100]" pageSize="20" showPageIndex="true" multiSelect="true"> <div property="columns"> <!-- 定义列 --> </div> </div> <script type="text/javascript"> // 初始化 DataGrid var datagrid = new nui.datagrid("datagrid1", { onBeforeLoad: function (e) { e.cancel = true; let pageIndex = e.data.pageIndex; let pageSize = e.data.pageSize; // 调用自定义方法加载数据 loadCustomData(pageIndex, pageSize); } }); // 自定义加载数据方法 function loadCustomData(pageIndex, pageSize) { const url = "com.primeton.train.expense.expenseQuery.biz.ext"; // 数据接口地址 const params = { pageIndex: pageIndex, pageSize: pageSize }; // 使用 Ajax 加载数据 fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params) }) .then(response => response.json()) .then(data => { // 更新 DataGrid数据 datagrid.setData(data); // 假设返回的数据结构符合 DataGrid 的要求 }) .catch(error => console.error('Error:', error)); } </script> ``` #### 关键点解析 1. **DataGrid 初始化**:通过 `new nui.datagrid` 方法初始化 DataGrid 控件,并设置 `onBeforeLoad` 事件以拦截默认的 Ajax 请求。 2. **Ajax 数据加载**:在 `onBeforeLoad` 中取消默认请求 (`e.cancel = true`),然后调用自定义方法 `loadCustomData` 来手动发送 Ajax 请求[^2]。 3. **数据更新**:当 Ajax 请求成功后,使用 `datagrid.setData(data)` 方法将返回的数据绑定到 DataGrid 中[^2]。 #### 注意事项 - 确保返回的数据格式符合 DataGrid 的要求,通常需要包含 `total` 和 `rows` 字段。 - 如果需要分页功能,确保服务器端返回正确的分页信息(如总记录数、当前页码等)[^1]。 ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值