標籤:
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 shiyan4{ public partial class Form1 : Form { SqlDataAdapter adapter; DataTable table; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string varNumber = textBox1.Text.Trim(); if (varNumber ==""||varNumber ==null){MessageBox.Show("請輸入你要查詢的學號", "提示資訊",MessageBoxButtons.OK,MessageBoxIcon.Warning);} try {string connStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True"; SqlConnection conn = new SqlConnection(connStr); string sql = "select * from Table1 where 姓名=‘" + varNumber + "‘"; adapter = new SqlDataAdapter(sql, conn); SqlCommandBuilder builder = new SqlCommandBuilder(adapter); table = new DataTable(); adapter.Fill(table); dataGridView1.DataSource = table; //conn.Close(); } catch (Exception ee) { MessageBox.Show(ee.Message, "提示資訊", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void button2_Click(object sender, EventArgs e) { textBox1.Text = ""; dataGridView1.EndEdit(); try { adapter.Update(table); MessageBox.Show("儲存成功"); } catch (Exception ee) { MessageBox.Show(ee.Message, "儲存失敗"); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } }}
C# 實驗4 資料庫