/// <summary> /// 导入数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void toolStripMenuItem6_Click(object sender, EventArgs e) { var itemId = GetCurrentMItemId(); if (itemId != -1) { var dialog = new OpenFileDialog(); dialog.Filter = "txt文件(*.txt)|*.txt"; if (dialog.ShowDialog() == DialogResult.OK) { //打开数据查看窗口 var form = new FrmDisplayRawData(dialog.FileName) { Owner = this }; if (form.ShowDialog() == DialogResult.OK) { //获取数据查看窗口的数据,去掉“序号”列 var dataTable = ExtendMethodDataTable.UnIdentifyDataTable(form.DataTable); //加入“测项编号”列,并填入测项编号 dataTable.Columns.Add("测项编号", typeof(int)); dataTable.FillColumnByFixedValue("测项编号", itemId); //从数据库中查询到这个测项的数据 var dt = new DataTable(); var sql = "select * from {0} where 测项编号={1}"; sql = string.Format(sql, DaoObject.TnRData(), itemId); var adapter = new MySqlDataAdapter(sql, DaoObject.ConnectionString); var builder = new MySqlCommandBuilder(adapter); adapter.Fill(dt); //数据表合并 dt.Merge(dataTable, true, MissingSchemaAction.Error); //更新数据 var n = adapter.Update(dt); if (n > 0) { MessageBox.Show("导入成功!"); RefreshRawData(itemId); } } } } }
/// <summary> /// 用dataTable刷新DataGridView /// </summary> /// <param name="dataTable"></param> public void RefreshDataGridView(DataTable dataTable) { this.dataGridView1.DataSource = null; this.dataGridView1.DataSource = ExtendMethodDataTable.AddCheckColumn(dataTable); this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.MultiSelect = true; this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.AllowUserToResizeRows = false; this.dataGridView1.AllowUserToOrderColumns = false; this.dataGridView1.AllowUserToResizeColumns = false; // 按照单元格的内容决定列的宽度,最后一列填充DataGridView this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells; this.dataGridView1.Columns[this.dataGridView1.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; // 除了选择列可编辑之外,其他列不可编辑 for (int i = 1; i < this.dataGridView1.ColumnCount; i++) { this.dataGridView1.Columns[i].ReadOnly = true; } foreach (DataGridViewColumn column in dataGridView1.Columns) { column.SortMode = DataGridViewColumnSortMode.NotSortable; } }