溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Button控件與數(shù)據(jù)庫(kù)交互示例

發(fā)布時(shí)間:2024-08-31 14:41:48 來(lái)源:億速云 閱讀:82 作者:小樊 欄目:移動(dòng)開發(fā)

在這個(gè)示例中,我們將創(chuàng)建一個(gè)簡(jiǎn)單的Windows Forms應(yīng)用程序,其中包含一個(gè)Button控件和一個(gè)Label控件

  1. 首先,確保已安裝SQL Server并創(chuàng)建一個(gè)名為"TestDB"的數(shù)據(jù)庫(kù)。然后,在該數(shù)據(jù)庫(kù)中創(chuàng)建一個(gè)名為"Users"的表,包含以下列:Id(int,主鍵),Name(nvarchar(50))和Age(int)。

  2. 在Visual Studio中創(chuàng)建一個(gè)新的Windows Forms應(yīng)用程序項(xiàng)目。

  3. 從工具箱中,將一個(gè)Button控件和一個(gè)Label控件添加到Form上。

  4. 雙擊Button控件以生成Click事件處理程序。

  5. 在項(xiàng)目中添加對(duì)System.Data.SqlClient的引用。

  6. 在Form的代碼文件中,添加以下代碼:

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private SqlConnection _connection;

        public Form1()
        {
            InitializeComponent();

            // 連接字符串,根據(jù)實(shí)際情況修改
            string connectionString = "Server=localhost;Database=TestDB;Integrated Security=True";
            _connection = new SqlConnection(connectionString);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                // 打開數(shù)據(jù)庫(kù)連接
                _connection.Open();

                // 查詢數(shù)據(jù)庫(kù)中的用戶數(shù)量
                string query = "SELECT COUNT(*) FROM Users";
                using (SqlCommand command = new SqlCommand(query, _connection))
                {
                    int userCount = (int)command.ExecuteScalar();

                    // 更新Label控件的文本
                    label1.Text = $"用戶數(shù)量:{userCount}";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("發(fā)生錯(cuò)誤:" + ex.Message, "錯(cuò)誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 關(guān)閉數(shù)據(jù)庫(kù)連接
                if (_connection.State == System.Data.ConnectionState.Open)
                {
                    _connection.Close();
                }
            }
        }
    }
}

現(xiàn)在,當(dāng)您運(yùn)行應(yīng)用程序并單擊按鈕時(shí),應(yīng)用程序?qū)⑦B接到數(shù)據(jù)庫(kù),查詢用戶數(shù)量并將結(jié)果顯示在Label控件中。請(qǐng)注意,您需要根據(jù)實(shí)際情況修改連接字符串。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI