using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EntityFrameworkSample
{
public partial class Form1 : Form
{
bool blIsSearch = false;
private string strCellBegin = string.Empty;//変更前値
private string strCellEnd = string.Empty;//変更後値
ArrayList al = new ArrayList();//修改行索引列表
int TotalCheckBoxes = 0;
int TotalCheckedCheckBoxes = 0;
CheckBox HeaderCheckBox = null;
bool IsHeaderCheckBoxClicked = false;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
AddHeaderCheckBox();
HeaderCheckBox.KeyUp += new KeyEventHandler(HeaderCheckBox_KeyUp);
HeaderCheckBox.MouseClick += new MouseEventHandler(HeaderCheckBox_MouseClick);
this.dataGridView1.CellPainting += new DataGridViewCellPaintingEventHandler(dgvSelectAll_CellPainting);
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dgvSelectAll_CurrentCellDirtyStateChanged);
InitData();
PlusCheckBox();
}
#region checkBox表頭方法
private void dgvSelectAll_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex == 8)//e.ColumnIndex == 8:checkbox列
{
ResetHeaderCheckBoxLocation(e.ColumnIndex, e.RowIndex);
}
}
private void ResetHeaderCheckBoxLocation(int ColumnIndex, int RowIndex)
{
//Get the column header cell bounds
Rectangle oRectangle = this.dataGridView1.GetCellDisplayRectangle(ColumnIndex, RowIndex, true);
Point oPoint = new Point();
oPoint.X = oRectangle.Location.X + (oRectangle.Width - HeaderCheckBox.Width) / 2 + 1;
oPoint.Y = oRectangle.Location.Y + (oRectangle.Height - HeaderCheckBox.Height) / 2 + 1;
//Change the location of the CheckBox to make it stay on the header
HeaderCheckBox.Location = oPoint;
}
private void dgvSelectAll_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.CurrentCell is DataGridViewCheckBoxCell)
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (!IsHeaderCheckBoxClicked)
RowCheckBoxClick((DataGridViewCheckBoxCell)dataGridView1[e.ColumnIndex, e.RowIndex]);
}
private void RowCheckBoxClick(DataGridViewCheckBoxCell RCheckBox)
{
if (RCheckBox != null)
{
//Modifiy Counter;
if ((bool)RCheckBox.Value && TotalCheckedCheckBoxes < TotalCheckBoxes)
TotalCheckedCheckBoxes++;
else if (TotalCheckedCheckBoxes > 0)
TotalCheckedCheckBoxes--;
//Change state of the header CheckBox.
if (TotalCheckedCheckBoxes < TotalCheckBoxes)
HeaderCheckBox.Checked = false;
else if (TotalCheckedCheckBoxes == TotalCheckBoxes)
HeaderCheckBox.Checked = true;
}
}
//--
private void HeaderCheckBox_MouseClick(object sender, MouseEventArgs e)
{
HeaderCheckBoxClick((CheckBox)sender);
}
//--
private void HeaderCheckBox_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
HeaderCheckBoxClick((CheckBox)sender);
}
private void HeaderCheckBoxClick(CheckBox HCheckBox)
{
IsHeaderCheckBoxClicked = true;
foreach (DataGridViewRow Row in dataGridView1.Rows)
((DataGridViewCheckBoxCell)Row.Cells[8]).Value = HCheckBox.Checked;
dataGridView1.RefreshEdit();
TotalCheckedCheckBoxes = HCheckBox.Checked ? TotalCheckBoxes : 0;
IsHeaderCheckBoxClicked = false;
}
private void AddHeaderCheckBox()
{
HeaderCheckBox = new CheckBox();
HeaderCheckBox.Size = new Size(15, 15);
//Add the CheckBox into the DataGridView
this.dataGridView1.Controls.Add(HeaderCheckBox);
}
#endregion
/// <summary>
/// 修改方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//取得选中行的主键值
//行索引
int keyValue = Int32.Parse(this.dataGridView1.CurrentRow.Cells[0].Value.ToString());
USERS user = new USERS();
user.UserName = this.txtUserName.Text.Trim();
user.LoginName = this.txtLoginName.Text.Trim();
user.PassWord = Convert.ToInt32(this.txtPwd.Text.Trim());
user.Plane = this.txtPlane.Text.Trim();
user.Phone = this.txtPhone.Text.Trim();
user.Mail = this.txtMail.Text.Trim();
user.CardNo = this.txtCardNo.Text.Trim();
user.ID = keyValue;
if (MessageBox.Show("确定要编辑?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
EFDBEntities entity = new EFDBEntities();
entity.USERS.Attach(user);
entity.Entry(user).State = EntityState.Modified;
entity.SaveChanges();
InitData();
MessageBox.Show("更新成功!");
}
catch
{
MessageBox.Show("编辑数据错误,请检查数据?", "系统错误", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// 删除方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
int keyValue = Int32.Parse(this.dataGridView1.CurrentRow.Cells[0].Value.ToString());
USERS user = new USERS();
user.ID = keyValue;
if (MessageBox.Show("确定要删除?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
EFDBEntities entity = new EFDBEntities();
entity.USERS.Attach(user);
entity.Entry(user).State = EntityState.Deleted;
entity.SaveChanges();
InitData();
MessageBox.Show("削除成功!");
}
catch
{
}
}
}
/// <summary>
/// 検索操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
string strSearch = txtSearch.Text.Trim();
EFDBEntities entity = new EFDBEntities();
List<USERS> users = new List<USERS>();
if (string.IsNullOrEmpty(strSearch))
{
users = entity.USERS.ToList();
blIsSearch = true;
}
else
{
users = entity.USERS.ToList();
users = users.Where(p => p.LoginName.Contains(strSearch)).ToList();
}
this.dataGridView1.DataSource = users;
PlusCheckBox();
}
/// <summary>
/// データを登録する
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button5_Click(object sender, EventArgs e)
{
string strUserName = this.txtUserName.Text.Trim();
string strLoginName = this.txtLoginName.Text.Trim();
if (string.IsNullOrEmpty(strUserName) || string.IsNullOrEmpty(strLoginName))
{
MessageBox.Show("ユーザー名又は登録名が空ですので、データをチェックして下さい!");
}
else
{
USERS user = new USERS();
user.UserName = strUserName;
user.LoginName = strLoginName;
user.PassWord = Convert.ToInt32(this.txtPwd.Text.Trim());
user.Plane = this.txtPlane.Text.Trim();
user.Phone = this.txtPhone.Text.Trim();
user.Mail = this.txtMail.Text.Trim();
user.CardNo = this.txtCardNo.Text.Trim();
if (UserCheck(strUserName))
{
MessageBox.Show("新規ユーザーが存在しているので、新規できませんでした!");
}
else
{
try
{
EFDBEntities entity = new EFDBEntities();
entity.USERS.Add(user);
entity.SaveChanges();
InitData();
MessageBox.Show("新規データ成功。");
}
catch
{
MessageBox.Show("新規操作中エラーがあります、データをチェックして下さい!");
}
}
}
}
/// <summary>
/// 検索条件をクリアー
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnClearSearch_Click(object sender, EventArgs e)
{
this.txtSearch.Text = string.Empty;
}
/// <summary>
/// データー初期化
/// </summary>
private void InitData()
{
EFDBEntities entity = new EFDBEntities();
List<USERS> users = new List<USERS>();
users = entity.USERS.ToList();
this.dataGridView1.DataSource = users;
TotalCheckBoxes = this.dataGridView1.RowCount;
TotalCheckedCheckBoxes = 0;
}
/// <summary>
/// GridView中添加checkbox列方法
/// </summary>
private void PlusCheckBox()
{
DataGridViewColumn myCol = new DataGridViewCheckBoxColumn();
dataGridView1.Columns.Add(myCol);
dataGridView1.Columns[8].Width = 42;
}
private void button1_Click(object sender, EventArgs e)
{
CommentForm1 cmtForm1 = new CommentForm1();
cmtForm1.ShowDialog();
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
//取得选中行的主键值
//行索引
if (blIsSearch)
{
InitData();
blIsSearch = false;
}
int keyValue = Int32.Parse(this.dataGridView1.CurrentRow.Cells[0].Value.ToString());
EFDBEntities entity = new EFDBEntities();
List<USERS> users = entity.USERS.ToList();
USERS userPer = users.SingleOrDefault(p => p.ID == keyValue); //ID=keyValue的单个user类
if (userPer != null)
{
txtUserName.Text = userPer.UserName;
txtLoginName.Text = userPer.LoginName;
txtPwd.Text = userPer.PassWord.ToString();
txtPlane.Text = userPer.Plane;
txtPhone.Text = userPer.Phone;
txtMail.Text = userPer.Mail;
txtCardNo.Text = userPer.CardNo;
}
}
/// <summary>
/// リストデータを更新する
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button6_Click(object sender, EventArgs e)
{
if (al.Count > 0)
{
BatchUpdate(al);
}
else
{
MessageBox.Show("无更新数据");
}
}
/// <summary>
/// ユーザー存在チェック
/// </summary>
/// <param name="userName">ユーザー名</param>
/// <returns>true:存在 false:不存在</returns>
private bool UserCheck(string userName)
{
bool retVal = false;
EFDBEntities entity = new EFDBEntities();
List<USERS> users = entity.USERS.ToList();
USERS userPer = users.SingleOrDefault(p => p.UserName == userName); //ID=keyValue的单个user类
if (userPer != null)
{
retVal = true;
}
return retVal;
}
/// <summary>
/// 单元格进入编辑状态数据控制
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
//判断点击列是否为checkbox列
if(dataGridView1.CurrentCell.ColumnIndex != 8)
{
//更改前の値
strCellBegin = dataGridView1.CurrentCell.Value.ToString();
}
}
/// <summary>
/// 单元格结束编辑状态数据控制
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex != 8)
{
//更改後の値
strCellEnd = dataGridView1.CurrentCell.Value.ToString();
if (strCellBegin != strCellEnd)
{
//设置单元格背景色
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.LightPink;
//被更改行索引
//int keyValue = Int32.Parse(this.dataGridView1.CurrentRow.Cells[0].Value.ToString());
int rowIndex = Int32.Parse(this.dataGridView1.CurrentRow.Index.ToString());
al.Add(rowIndex);
}
strCellBegin = string.Empty;
strCellEnd = string.Empty;
}
}
/// <summary>
/// 批量更新操作
/// </summary>
/// <param name="updRowAL"></param>
private void BatchUpdate(ArrayList updRowAL)
{
if (MessageBox.Show("确定要批量更新?", "系统提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
try
{
for (int i = 0; i < updRowAL.Count; i++)
{
DataGridViewRow dgvr = dataGridView1.Rows[Convert.ToInt32(updRowAL[i])];
string cellKey = dgvr.Cells[0].Value.ToString();//你自己要获取的数据
string cellUserName = dgvr.Cells[1].Value.ToString();
string cellLoginName = dgvr.Cells[2].Value.ToString();
string cellPassWord = dgvr.Cells[3].Value.ToString();
string cellPlane = dgvr.Cells[4].Value.ToString();
string cellPhone = dgvr.Cells[5].Value.ToString();
string cellMail = dgvr.Cells[6].Value.ToString();
string cellCardNo = dgvr.Cells[7].Value.ToString();
USERS user = new USERS();
user.UserName = cellUserName;
user.LoginName = cellLoginName;
user.PassWord = Convert.ToInt32(cellPassWord);
user.Plane = cellPlane;
user.Phone = cellPhone;
user.Mail = cellMail;
user.CardNo = cellCardNo;
user.ID = Convert.ToInt32(cellKey);
EFDBEntities entity = new EFDBEntities();
entity.USERS.Attach(user);
entity.Entry(user).State = EntityState.Modified;
entity.SaveChanges();
}
InitData();
al.Clear();
MessageBox.Show("批量更新成功!");
}
catch
{
MessageBox.Show("批量更新发生错误,请检查数据?", "系统错误", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Error);
}
}
}
}
}