mainform.cs

来自「Address book helps you look up your addr」· CS 代码 · 共 55 行

CS
55
字号
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DataGridView2Db {
  public partial class MainForm: Form {
    public MainForm() {
      InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e) {
      this.regionTableAdapter.Fill(this.northwindDataSet.Region);
      //resize the column once, but allow the ussers to change it.
      this.regionDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
    }


    private DataRow LastDataRow = null; //tracks for the PositionChanged event the last row

    /// <summary>
    /// Checks if there is a row with changes and writes it to the database
    /// </summary>
    private void UpdateRowToDatabase() {
      if (LastDataRow!=null) {
        if (LastDataRow.RowState==DataRowState.Modified) {
          regionTableAdapter.Update(LastDataRow);
        }
      }
    }

    
    private void regionBindingSource_PositionChanged(object sender, EventArgs e) {
      // if the user moves to a new row, check if the last row was changed
      BindingSource thisBindingSource = (BindingSource)sender;
      DataRow ThisDataRow=((DataRowView)thisBindingSource.Current).Row;
      if (ThisDataRow==LastDataRow) {
        // we need to avoid to write a datarow to the database when it is still processed. Otherwise we get a problem
        // with the event handling of the dataTable.
        throw new ApplicationException("It seems the PositionChanged event was fired twice for the same row");
      }

      UpdateRowToDatabase();
      //track the current row for next PositionChanged event
      LastDataRow = ThisDataRow;
    }

    private void MainForm_FormClosed(object sender, FormClosedEventArgs e) {
      UpdateRowToDatabase();
    }
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?