SQL學習筆記之DataGridView學習
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 醫療卡號
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學習