DataAdapter = new MySqlDataAdapter("Select * from " + SelectObject.Text + ";", MyLib.MyConnection); //Создаём адаптер-посредник CommandBuilder = new MySqlCommandBuilder(DataAdapter); // Для адаптера доступно UPDATE dTable = new DataTable(); this.dGrid1.DataSource = dTable; MyLib.MySQLOpen(); dTable.Clear(); DataAdapter.Fill(dTable); // Всасываем данные из адаптера в dTable int NRows = dTable.Rows.Count, NColumns = dTable.Columns.Count; // Как в БД int NRows2 = dGrid1.Rows.Count, NColumns2 = dGrid1.Columns.Count; // <b>Нули!!!</b> dGrid1.DataSource = dTable; // Связываем данные с демонстрируемым элементом dGrid1 формы MyLib.MySQLClose(); |
2 answers
Hello. Perhaps this full example will help you deal with your question. It seems to me that in a simple but complete example, it is easier to understand than in a code snippet. There is an Excel file that is filled with data. The program reads this data and fills in a multi-line text field and DataGridView.
Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; //подключить пространство имен using System.Data.OleDb; namespace _0003 { public partial class Form1 : Form { string connectionString = null; OleDbConnection connection; string sql = null; public Form1() { InitializeComponent(); textBox1.ReadOnly = true; } private void button1_Click(object sender, EventArgs e) { openFileDialog1.DefaultExt = "*.xlsx;*.xls"; openFileDialog1.Filter = "Excel 2007 и выше(*.xlsx)|*.xlsx|Excel 2003(*.xls)|*.xls"; openFileDialog1.Title = "Выберите документ для загрузки данных"; openFileDialog1.FileName = ""; if(openFileDialog1.ShowDialog() == DialogResult.OK) { textBox1.ReadOnly = false; textBox1.Text = openFileDialog1.FileName; connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + openFileDialog1.FileName + @";Extended Properties=""Excel 12.0 Xml; HDR = YES"";"; using(connection = new OleDbConnection(connectionString)) { try { connection.Open(); //получаем список листов в Excel файле DataTable schemaTable = connection.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); //выбираем название первого листа string sheet1 = (string)schemaTable.Rows[0].ItemArray[2]; sql = String.Format("SELECT * FROM [{0}]", sheet1); //заполняем многострочное поле OleDbCommand cmd = new OleDbCommand(sql, connection); OleDbDataReader reader = cmd.ExecuteReader(); while(reader.Read()) { textBox2.Text += " " + reader[0] + " " + reader[1] + " " + Math.Round(decimal.Parse(reader[2].ToString()), 2).ToString() + " " + "\r\n"; } //заполняем таблицу //при помощи класса OleDbDataAdapter и его метода Fill данные загружаются в Dataset System.Data.OleDb.OleDbDataAdapter ad = new System.Data.OleDb.OleDbDataAdapter(sql, connection); DataSet ds = new DataSet(); ad.Fill(ds); //создаем таблицу, которая будет источником данных для таблицы dataGridView DataTable tb = ds.Tables[0]; dataGridView1.DataSource = tb; } catch(Exception exc) { MessageBox.Show("Ошибка соединения!\n" + exc); } finally { connection.Close(); } } } } } } |
When I recreated the Windows Form application from scratch, abandoning all the Studio wizards / masters for communicating with the database, it all worked. This decision was prompted to me by the fact that previously similar code worked normally in the case of SQLite database without these lotions. Thanks for the tip though.
|
