0
私は、ボタンを変更してから同じ変更を行い、更新後に変更する前に同じ値がある場合は、DataGridViewを使用します。DataGridviewの変更を保存します。
ボタン1 - DataGridViewの ボタン4でレコードを更新することができます - - DataGridViewの ボタン3を更新 - 新しいレコード ボタン2を挿入し、ボタン5 の変更を保存 - キャンセルこれはかなり包括的である
using System;
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;
using System.Data.SqlClient;
using System.Configuration;
namespace IS
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
LoadTable();
label1.Text = "User: " + User.name + " " + User.surename;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void LoadTable()
{
using (SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\***\Documents\Visual Studio 2015\Projects\***\Database1.mdf;Integrated Security=True;Connect Timeout=30"))
using (SqlCommand query = new SqlCommand("Select FirstName, LastName, Login, Email from Users", connection))
{
try
{
SqlDataAdapter Adapter = new SqlDataAdapter();
Adapter.SelectCommand = query;
DataTable UsersTable = new DataTable();
Adapter.Fill(UsersTable);
BindingSource UserTableSource = new BindingSource();
UserTableSource.DataSource = UsersTable;
dataGridView1.DataSource = UserTableSource;
Adapter.Update(UsersTable);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void label1_Click_1(object sender, EventArgs e)
{
}
private void UserManageToolStripMenuItem_Click(object sender, EventArgs e)
{
panel2.Visible = true;
}
private void button1_Click(object sender, EventArgs e)
{
Form3 form3 = new Form3();
form3.FormClosing += new FormClosingEventHandler(this.Form3_FormClosing);
form3.Show();
}
private void button2_Click(object sender, EventArgs e)
{
LoadTable();
}
private void Form3_FormClosing(object sender, FormClosingEventArgs e)
{
LoadTable();
}
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
button4.Visible = true;
button5.Visible = true;
}
private void button4_Click(object sender, EventArgs e)
{
try
{
SqlDataAdapter sda = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder();
DataTable dt = new DataTable();
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
dataGridView1.ReadOnly = true;
button4.Visible = false;
button5.Visible = false;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button5_Click(object sender, EventArgs e)
{
LoadTable();
button4.Visible = false;
button5.Visible = false;
}
}
}
[CRUD Operations with DataGridView、DataTable and TableAdapter](http://stackoverflow.com/a/36274706/3110834)をご覧ください。また、これはより迅速な解決策として:[バインディングソースからフォームのコントロールを自動生成する方法はありますか?](http://stackoverflow.com/a/38168317/3110834) –