一、知识点描述
1.DataTable对象用来保存单个表数据,在System.Data命名空间中定义。它包含由DataCloumnCollection表示集合以及由ConstraintCollection表示的约束集合,这两个共同定义表的架构。DataTable还包含DataRowCollection所表示的行的集合,而DataRowCollection则包含表中的数据。
2.DataTable的创建
1.使用相应的DataTable构造函数创建DataTable对象。
2.使用Add方法将其添加到DataTable对象的Tables集合中,将其添加到DataSet中。
二、示例代码及效果截图
private void btn_Load_Click(object sender, EventArgs e)
{
SqlConnection sqlConnection = new SqlConnection();
sqlConnection.ConnectionString =
"Server=(local);Database=EduBaseMenzhen;Integrated Security=sspi";
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "SELECT * FROM tb_Patients;";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
this.PatientTable = new DataTable();
sqlConnection.Open();
sqlDataAdapter.Fill(this.PatientTable);
sqlConnection.Close();
this.dgv_Course.Columns.Clear();
this.dgv_Course.DataSource = this.PatientTable;
this.dgv_Course.Columns["No"].HeaderText = "编号";
this.dgv_Course.Columns["Name"].HeaderText = "名称";
this.dgv_Course.Columns["Gender"].HeaderText = "性别";
this.dgv_Course.Columns["BirthDate"].HeaderText = "出生日期";
this.dgv_Course.Columns["PoliticalStatus"].HeaderText = "政治地位";
this.dgv_Course.Columns["Nationality"].HeaderText = "民族";
this.dgv_Course.Columns["Province"].HeaderText = "省";
this.dgv_Course.Columns["City"].HeaderText = "城市";
this.dgv_Course.Columns["IdentificationCard"].HeaderText = "身份证";
this.dgv_Course.Columns["Phone"].HeaderText = "电话";
this.dgv_Course.Columns["PatientsNo"].HeaderText = "编号";
}
private void btn_SearchByNo_Click(object sender, EventArgs e)
{
DataRow searchResultRow = this.PatientTable.Rows.Find(this.txb_CourseNo.Text.Trim());
DataTable searchResultTable = this.PatientTable.Clone();
searchResultTable.ImportRow(searchResultRow);
this.dgv_Course.DataSource = searchResultTable;
}
private void btn_SearchByName_Click(object sender, EventArgs e)
{
DataRow searchResultRow = this.PatientTable.Rows.Find(this.txb_CourseName.Text.Trim());
DataTable searchResultTable = this.PatientTable.Clone();
searchResultTable.ImportRow(searchResultRow);
this.dgv_Course.DataSource = searchResultTable;
}
三、思维导图