ที่เราต้องการแทรกและ value ที่ต้องการไปยังตำแหน่งดังกล่าว เมื่อการทำงานของ method
เสร็จสมบูรณ์เราก็จะได้ String ใหม่ที่มีการแทรก value เพิ่ม
สร้างฟอร์มมาเพื่อทำการเก็บค่า เมื่อทำการสร้างฟอร์มเสร็จตามที่ต้องการแล้วให้ทำการเชื่อมต่อฐานข้อมูล
โค้ด: เลือกทั้งหมด
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 test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void ShowSearchData()
{
string Conn = @"Data Source=DESKTOP-25R1MCQ\SQLEXPRESS;Initial
Catalog=test;Integrated Security=True"; //statementจะเป็นการเชื่อมต่อกับฐานข้อมูล Database
try{
SqlConnection CN = new SqlConnection(Conn);
SqlDataAdapter ADAP = new SqlDataAdapter("Select prefix_id,prefix_name from prefix
where prefix_id=@prefix_id", CN);
DataSet DS = new DataSet();
ADAP.Fill(DS, "prefix");
dataGridView1.DataSource = DS.Tables["prefix"]; //ตรงนี้คือนำตารางที่ต้องการมาโชว์ใน Gridview
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
ถ้าเราจะทำการ insert ข้อมูลลงในฐานข้อมูล ให้Double Click ที่ปุ่มเพิ่ม หรือปุ่มที่เราจะทำการ insert
โค้ด: เลือกทั้งหมด
private void insert_Click(object sender, EventArgs e)
{
prefixrecord record = new prefixrecord();
record.prefix_id = textBox1.Text;
record.prefix_name = textBox2.Text;
string query = @"INSERT INTO prefix
(prefix_id, prefix_name)
VALUES
(@prefix_id, @prefix_name)";
List<SqlParameter> sqlParams = new List<SqlParameter>();
sqlParams.Add(new SqlParameter("@prefix_id", textBox1.Text));
sqlParams.Add(new SqlParameter("@prefix_name", textBox2.Text));
if (DB.ExecuteNonQuery(query, sqlParams))
{
ClearInput(); //คือ method ที่เอาไว้เคลียร์ค่าในช่องว่าง
}
else
{
MessageBox.Show("เกิดข้อผิดพลาด ไม่สามารถเพิ่มข้อมูลได้" , "เกิดข้อผิดพลาด", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
โค้ด: เลือกทั้งหมด
private void ClearInput()
{
textBox1.Text = "";
textBox2.Text = "";
}
โค้ด: เลือกทั้งหมด
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
textBox1.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString();
textBox2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
}