このプログラムは、挿入、更新用に作成しました
C#データベース名からデータセットを使用すると、誰でもこのコードをチェックできますか?構文に何を書くべきか教えてください。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Insert_update_delete
{
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
Loadlist();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtId.Text != "" & txtName.Text != "")
{
cn.Open();
cmd.CommandText = "Insert into info (Id, Name) Values('"+txtId.Text+"' , '"+txtName.Text+"')";
cmd.ExecuteNonQuery();(it is showing error here )
cmd.Clone();
MessageBox.Show("Record Inserted!");
cn.Close();
txtId.Text = "";
txtName.Text = "";
Loadlist();
}
}
private void Loadlist()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
cn.Open();
cmd.CommandText = "Select * From info";
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
listBox1.Items.Add(dr[0].ToString());
listBox2.Items.Add(dr[1].ToString());
}
}
cn.Close();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox l = sender as ListBox;
if(l.SelectedIndex != -1)
{
listBox1.SelectedIndex = l.SelectedIndex;
listBox2.SelectedIndex = l.SelectedIndex;
txtId.Text = listBox1.SelectedItem.ToString();
txtName.Text = listBox2.SelectedItem.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
if (txtId.Text != "" & txtName.Text != "")
{
cn.Open();
cmd.CommandText = "Delete from info where id*'"+txtId.Text+"' and name*'"+txtName.Text+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Deleted");
Loadlist();
txtId.Text = "";
txtName.Text = "";
}
}
private void button3_Click(object sender, EventArgs e)
{
if (txtId.Text != "" & txtName.Text != "" & listBox1.SelectedIndex != -1)
{
cn.Open();
cmd.CommandText = "Update info set id='"+txtId.Text+"', name='"+txtName.Text+"' where id='"+listBox1.SelectedItem.ToString()+"' and name= '"+listBox2.SelectedItem.ToString()+"'";
cmd.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Record Updated");
Loadlist();
txtId.Text = "";
txtName.Text = "";
}
}
}
}
これで問題なく動作することは間違いありません。確認してください。