基於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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM