การ insert ข้อมูลจาก textbox ลงในฐานข้อมูล โดยใช้ภาษา C#

แนะนำ สอบถาม ภาษา C สำหรับผู้เริ่มต้น ภาษา Java ภาษา Python

Moderator: mindphp, ผู้ดูแลกระดาน

moo1997
PHP Full Member
PHP Full Member
โพสต์: 38
ลงทะเบียนเมื่อ: 20/07/2020 10:07 am

การ insert ข้อมูลจาก textbox ลงในฐานข้อมูล โดยใช้ภาษา C#

โพสต์ที่ยังไม่ได้อ่าน โดย moo1997 »

การ insert เป็น Method ในการแทรก String ไปยังตำแหน่งที่ต้องการ โดยการระบุ index
ที่เราต้องการแทรกและ value ที่ต้องการไปยังตำแหน่งดังกล่าว เมื่อการทำงานของ method
เสร็จสมบูรณ์เราก็จะได้ String ใหม่ที่มีการแทรก value เพิ่ม

สร้างฟอร์มมาเพื่อทำการเก็บค่า
insert.jpg
insert.jpg (18.81 KiB) Viewed 1874 times
เมื่อทำการสร้างฟอร์มเสร็จตามที่ต้องการแล้วให้ทำการเชื่อมต่อฐานข้อมูล

โค้ด: เลือกทั้งหมด

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);
}
}
method ที่เอาไว้เคลียร์ค่าในช่องว่าง

โค้ด: เลือกทั้งหมด

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();
}
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 34