zoukankan      html  css  js  c++  java
  • 基于Winform框架DataGridView控件的SqlServer数据库查询展示功能的实现

    关键词:Winform、DataGridView、SqlServer

     一个基于winform框架的C/S软件,主要实现对SqlServer数据库数据表的实时查询。

    一、为DataGridView添加数据源并对DataGridView内容进行操作

    (1)引入域名空间:using System.Data.SqlClient;

    (2)定义类变量并实例化对象

    protected static String strCon = "Data Source=192.168.1.1;Initial Catalog=Monitor;Integrated Security=False;User ID=sa;Password=....";
    protected SqlConnection con = new SqlConnection(strCon); 

    “Integrated Security”字段为True,表示使用Windows身份验证方式进行数据库登录,登录ID和密码没用;为False,表示使用SqlServer身份验证方式登录数据库。该字段还可设置为SSPI,相当于True。

    (3)编写函数

    函数功能:设计SQL查询语句,连接数据库获取查询结果并填充DataGridView控件,然后根据数据内容修改单元格背景颜色。添加定时器周期刷新,直接将函数在定时器方法中调用即可。

    如果SQL语句查询出来的结果展示的时候需要进行简单处理,建议在SQL查询的时候进行。创建SQL语句命令对象,执行查询返回结果集。得到结果集之后,手动给DataGridView绑定数据源,利用SqlDataReader填充DataGridView。注意数据库连接的打开与关闭。这一步可以在DataGridView控件上展示原始的SQL查询出来的数据。如果需要在Form点开的时候进行初始化,在Form1_Load函数中调用该函数即可。

    右键Form选择属性,然后选择Form方法,找到Load方法,双击创建函数,进行加载窗体的初始化函数编写。

    //使用SqlDataReader填充DataGridView。cmd为创建命令对象,指定要执行sql语句与连接对象con返回的结果
    //SqlCommand cmd = new SqlCommand(sql, con);String sql = "";
    SqlDataReader dr = cmd.ExecuteReader(); BindingSource bs = new BindingSource(); bs.DataSource = dr; this.dataGridView1.DataSource = bs;  

    得到数据源后可以根据需求对DataGridView的数据展示进行相应的处理。列的宽度和行的高度的自动调整。数据源标题的修改,既可以在SQL查询的时候进行,也可以查询出结果后对DataGridView的HeaderText进行修改,例如:

    this.dataGridView1.Columns["Status_Name"].HeaderText = "连接状态";
    

    其中“Status_Name”为SQL语句查询出来的数据列的列名,修改HeaderText只是修改用户看到列名(HeaderText),实际的操作还是针对实际查询的列名(Name),如果需要根据列的内容进行对单元格的一些操作,查询列的时候需要查询Name,例如如果需要根据单元格内容修改单元格背景颜色,查询“Status_Name”的值而不是查询"连接状态"的值,代码如下:

    //根据连接状态改变状态表的背景颜色
    int rowCount = this.dataGridView1.Rows.Count;
    for (int i = 0; i < rowCount; i++)
    {
    	if (this.dataGridView1.Rows[i].Cells["Status_Name"].Value.ToString() == "正常")
    		this.dataGridView1.Rows[i].Cells["Status_Name"].Style.BackColor = Color.Green;
    	else
    		this.dataGridView1.Rows[i].Cells["Status_Name"].Style.BackColor = Color.Red;
    }
    

     在每条记录后面加一个button,每个button上都有操作的文本提示。DataGridView控件中,提供了一种列的类型,叫 DataGridViewButtonColumn ,列类型是展示为一个 按钮,可以给button赋予相应的text,并且此button可以用来做处理事件的判断依据。但是这个列button只是渲染出来的样式,是画出来的效果。所以对于传统意义的button的东西在这里不适用。button事件对应的是CellContentClick函数。

    //增加button,查询历史信息
    DataGridViewButtonColumn button = new DataGridViewButtonColumn();
    button.Name = "History";
    button.HeaderText = "历史信息";
    button.DefaultCellStyle.NullValue = "历史信息";
    this.dataGridView1.Columns.Add(button);
    

     简易的参考界面如下 

    该函数完整代码如下,根据需求调用即可

    //查询传感器状态表,获取开停传感器状态信息
    private void KTSQL()
    {
        try
        {
            con.Open();
            //数据表查询
            String sql = "SELECT distinct b.DEVICE_ID,a.Sensor_Name,c.Status_Name,a.Placement,a.Save_Time,(CASE WHEN (a.Value = '1' )THEN '开' ELSE '停' END) " +
                         "as KorT FROM [KJ83-2006].dbo.M_Active_View as a,[KJ83-2006].dbo.M_State as c,[FkMonitor].[dbo].[T_DEVICE_INFO] as b " +
                         "WHERE   c.Status_Id = a.Status  and a.Node_Id = b.MAC_ADDRESS   and b.TYPE_ID='TF' and (a.Sensor_Name = '开停') order by DEVICE_ID";
            //创建命令对象,指定要执行sql语句与连接对象conn
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandTimeout = 180;
            //执行查询返回结果集
            SqlDataReader sdr = cmd.ExecuteReader();
            ////使用SqlDataReader填充DataGridView 
            BindingSource bs = new BindingSource();
            bs.DataSource = sdr;
            this.dataGridView1.DataSource = bs;
        }
        finally
        {
            con.Close();
        }
    
        //修改数据源标题
        this.dataGridView1.Columns["DEVICE_ID"].HeaderText = "编号";
        this.dataGridView1.Columns["Sensor_Name"].HeaderText = "传感器类型";
        this.dataGridView1.Columns["Status_Name"].HeaderText = "连接状态";
        this.dataGridView1.Columns["Placement"].HeaderText = "位置";
        this.dataGridView1.Columns["KorT"].HeaderText = "开停状态";
        //this.dataGridView1.Columns["KorT"].FillWeight = 1000;
        this.dataGridView1.Columns["Save_Time"].HeaderText = "监测时间";
    
        //根据连接状态改变状态表的背景颜色
        int rowCount = this.dataGridView1.Rows.Count;
        for (int i = 0; i < rowCount; i++)
        {
            if (this.dataGridView1.Rows[i].Cells["Status_Name"].Value.ToString() == "正常")
                this.dataGridView1.Rows[i].Cells["Status_Name"].Style.BackColor = Color.Green;
            else
                this.dataGridView1.Rows[i].Cells["Status_Name"].Style.BackColor = Color.Red;
        }
        //增加button,查询历史信息
        button.Name = "History";
        button.HeaderText = "历史信息";
        button.DefaultCellStyle.NullValue = "历史信息";
        this.dataGridView1.Columns.Add(button);
    }
    View Code

    二、历史信息查询事件的实现

    button列展示之后的点击事件函数如下,主要分为两部分,捕捉button列的点击,然后根据列名获取需要的数据。之后可以根据获取的单元格的值进行相应的操作。获取选中行的某个数据需要先获取选中行的行数,然后根据列名或者列的编号获取单元格值。

    //查询历史状态信息
    private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
    {
    	//点击的是button列
    	if (dataGridView1.Columns[e.ColumnIndex].Name == "History" && e.RowIndex >= 0)
    	{
    		//获取该行开停的编号
    		int a = dataGridView1.CurrentRow.Index;
    		string str = dataGridView1.Rows[a].Cells["DEVICE_ID"].Value.ToString();
    	}
    
    }
    

     完整代码链接:https://coding.net/u/DreamQ/p/TFStatus/git

     参考文章:

    C# DataGridView绑定数据源的几种常见方式    https://www.cnblogs.com/arxive/p/5943850.html

    C# DataGridView如何获取选中行的某个数据   https://blog.csdn.net/hejisan/article/details/52688972

    C#中关于DataGridView行和列的背景色-前景色设置  https://blog.csdn.net/wangzhen209/article/details/51744518

  • 相关阅读:
    ajaxfileupload.js类实现异步文件上传
    设计模式代理
    状态码的分析
    图片的格式的分析、 图片优化
    BFC
    css3 的新属性
    二列布局、三列布局总结
    position的定义
    new Vue 发生了什么
    数据驱动
  • 原文地址:https://www.cnblogs.com/dreamq/p/10255512.html
Copyright © 2011-2022 走看看