1. 程式人生 > >SQL學習筆記之DataGridView學習

SQL學習筆記之DataGridView學習

.com rtti 應用程序 頻率 sele 卡號 res lin 說明

SQL學習筆記之DataGridView學習

:DataGridView介紹

使用 DataGridView 控件,可以顯示和編輯來自多種不同類型的數據源的表格數據。

: DataGridView的使用

當需要在 Windows 窗體應用程序中顯示表格數據時,請首先考慮使用 DataGridView 控件.若要以小型網格顯示只讀值,或者若要使用戶能夠編輯具有數百萬條記錄的表,DataGridView 控件將為您提供可以方便地進行編程以及有效地利用內存的解決方案(引自百度百科)

以上很清楚的說明了DataGridView的作用及使用。

三:思維導圖

技術分享圖片

四:舉例

(1)載入數據到DataGridView

代碼:

SqlConnection sqlConnection = new SqlConnection();

sqlConnection.ConnectionString =

"Server=(local);Database=huli;Integrated Security=sspi";

SqlCommand sqlCommand = sqlConnection.CreateCommand();

sqlCommand.CommandText =

"select userid as 醫療卡號

,username as 姓名,p_jibing as 患病名稱,p_chuanran as 傳染,starttime as 入院時間,p_tiwen as 體溫,p_huxi as 呼吸頻率,p_xueyagao as 舒張壓,p_xueyadi as 收縮壓,p_zhusu as 主訴,p_xianbingshi as 現病史,p_zhenduanxinxi as 診斷信息,p_guomingshi as 過敏史 from tb_patient";

this.t = new DataTable();

SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();

sqlDataAdapter.SelectCommand = sqlCommand;

sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;

sqlConnection.Open();

sqlDataAdapter.Fill(this.t);

sqlConnection.Close ();

this.CourseViewByName = new DataView();

this.CourseViewByName.Table = this.t;

this.CourseViewByName.Sort = "姓名 ASC";

SqlDataAdapter da = new SqlDataAdapter();

da.SelectCommand = sqlCommand;

DataSet d = new DataSet();

da.Fill(d, "tb_patient");

dataGridView1.DataSource = d;

dataGridView1.DataMember = "tb_patient";

sqlConnection.Close();

技術分享圖片

(2)搜索DataGridView中數據

代碼:

DataRow searchResultRow = this.t.Rows.Find(this.txt_card.Text.Trim());

DataTable searchResultTable = this.t.Clone();

searchResultTable.ImportRow(searchResultRow);

this.dataGridView1.DataSource = searchResultTable;

註意:此方法必須是搜索主鍵

技術分享圖片

以下方法可以搜索任何列

DataRowView[] searchResultRowViews =

this.CourseViewByName.FindRows(this.txt_name.Text.Trim());

DataTable searchResultTable = this.t.Clone();

foreach (DataRowView dataRowView2 in searchResultRowViews)

{

searchResultTable.ImportRow(dataRowView2.Row);

}

this.dataGridView1.DataSource = searchResultTable;

技術分享圖片

SQL學習筆記之DataGridView學習