[C#] 检索数据库并用DataGridView 控件显示数据.

练习点:

数据库读取数据并保存在一个集合中.

使用DataGridView来显示数据.


1  Form1 用于用户登录验证


Form1 Code

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;

namespace DataGridViewTest2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text;
            string password = txtPassword.Text;

            DBConnect dbc = new DBConnect();

            int s = dbc.UserLogin(username, password);

            if (1 == s)
            {
                MessageBox.Show("Incorrect Username");
            }
            if (2 == s)
            {
                MessageBox.Show("Incorrect Password");
            }
            if(0 == s)
            {
                Form2 form2 = new Form2(this);
                //this.Hide();
                form2.ShowDialog();
            }

        }
    }
}

2. Form2, 用记显示数据, 它只有一个DataGridView控件


Form2 Code

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.Collections;

namespace DataGridViewTest2
{
    public partial class 
  • 4
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
非常抱歉,我误解了你的问题。要使用C#DataGridView控件连接数据库,你可以遵循以下步骤: 1. 创建一个DataGridView控件并将其添加到你的窗体。 2. 使用SqlConnection类建立数据库连接,就像我之前提到的那样。 3. 构建一个查询或命令来从数据库检索数据。 4. 创建一个SqlDataAdapter对象,并使用它来填充一个DataTable或DataSet对象。 5. 将DataTable或DataSet对象分配给DataGridView控件的DataSource属性。 以下是一个示例代码,演示如何将DataGridView数据库连接起来: ```csharp using System.Data; using System.Data.SqlClient; using System.Windows.Forms; // 创建数据库连接字符串 string connectionString = "Data Source=服务器名;Initial Catalog=数据库名;User ID=用户名;Password=密码"; // 创建SqlConnection对象 SqlConnection connection = new SqlConnection(connectionString); // 创建查询语句 string query = "SELECT * FROM 表名"; try { // 打开数据库连接 connection.Open(); // 创建SqlDataAdapter对象 SqlDataAdapter adapter = new SqlDataAdapter(query, connection); // 创建DataTable对象 DataTable dataTable = new DataTable(); // 使用SqlDataAdapter填充DataTable adapter.Fill(dataTable); // 关闭数据库连接 connection.Close(); // 将DataTable分配给DataGridView的DataSource属性 dataGridView1.DataSource = dataTable; } catch (SqlException ex) { // 处理连接失败的异常 MessageBox.Show("连接到数据库时出错: " + ex.Message); } ``` 这段代码假设你已经在窗体上添加了一个名为dataGridView1的DataGridView控件。你需要将"服务器名"、"数据库名"、"用户名"、"密码"和"表名"替换为你自己的实际信息。 这样,当你运行应用程序时,DataGridView控件显示数据库检索到的数据。 希望这能满足你的需求!如果还有其他问题,请随时提问。
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值