Вывести данные на DataGrid из кода
От: DemAS http://demas.me
Дата: 18.03.03 11:40
Оценка:
Пробую так:

Config cfg = Config.Instance;
string connectionString = cfg.connectionString;
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();

OleDbDataAdapter adapter = new OleDbDataAdapter("select * from Balls", conn);
DataSet ds = new DataSet();            
            
adapter.Fill(ds);
dataGrid.SetDataBinding(ds, "Balls");


Все это делаю в Load формы, на которой расположен DataGrid.

Вот так программа ругается при попытке открыть эту форму.

An unhandled exception of type 'System.ArgumentException' occurred in system.windows.forms.dll

Additional information: Can't create a child list for field Balls.

Вообще может я не то все делаю. Мне надо результат SELECT вывести на Grid, так чтобы пользователь мог просматривать и редактировать его.

P.S. Немного оффтопа — в Дельфи все было просто — ADOConnection, ADOQuery, DataSet и DataGrid. Как это реализовать в C# ?


Заранее благодарен.
... <<Слушаю Van Halen — Somebody Get Me A Doctor >>

22.12.03 17:45: Перенесено модератором из '.NET' — AVK
Re: Вывести данные на DataGrid из кода
От: SCS  
Дата: 18.03.03 11:48
Оценка: 2 (1)
Здравствуйте, DemAS, Вы писали:

сделай либо явное заполнение конкретной таблицы
adapter.Fill(ds, "Balls");

либо перемапь имена перед fill
adapter.TableMappings.Add("Table","Balls");

PS посмотри, под какими именами адаптер возвращает таблицы
SCS
Re[2]: Вывести данные на DataGrid из кода
От: DemAS http://demas.me
Дата: 18.03.03 15:59
Оценка:
Здравствуйте, SCS, Вы писали:

SCS>Здравствуйте, DemAS, Вы писали:


SCS>сделай либо явное заполнение конкретной таблицы

SCS>
SCS>adapter.Fill(ds, "Balls");
SCS>



Спасибо. Форма запустилась.

Но почему-то когда я изменяю данные в гриде, изменения не отображаются на базе данных. Если второй раз открыть туже самую форму, все изменения уже потеряны

Что еще необходимо сделать ?
... <<Слушаю Van Halen — Unchained >>
Re[3]: Вывести данные на DataGrid из кода
От: Alex Medvedev  
Дата: 18.03.03 16:00
Оценка: 2 (1)
Здравствуйте, DemAS, Вы писали:

DAS>Здравствуйте, SCS, Вы писали:


SCS>>Здравствуйте, DemAS, Вы писали:


SCS>>сделай либо явное заполнение конкретной таблицы

SCS>>
SCS>>adapter.Fill(ds, "Balls");
SCS>>


DAS>

DAS> Спасибо. Форма запустилась.

DAS> Но почему-то когда я изменяю данные в гриде, изменения не отображаются на базе данных. Если второй раз открыть туже самую форму, все изменения уже потеряны


DAS> Что еще необходимо сделать ?


DAS>


Необходимо вызвать AcceptChanges.
Re[3]: Вывести данные на DataGrid из кода
От: SCS  
Дата: 18.03.03 16:10
Оценка: 2 (1)
Здравствуйте, DemAS, Вы писали:
DAS> Но почему-то когда я изменяю данные в гриде, изменения не отображаются на базе данных. Если второй раз открыть туже самую форму, все изменения уже потеряны
изменения в базу попадают из таблиц по
adapter.Update(ds.Tables["Balls"]);

естест-но, команды на INSERT, UPDATE и DELETE должны быть построены или в дизайнере или через OleDbCommandBuilder
метод update вызываешь программно: или по кнопке на форме или при выходе из формы (например, через вопрос "Данные изменены. Сохранить изменения ?")

запрос изменений через ds.GetChanges
SCS
Re[4]: Вывести данные на DataGrid из кода
От: DemAS http://demas.me
Дата: 18.03.03 16:11
Оценка:
Здравствуйте, Alex Medvedev, Вы писали:

AM>Необходимо вызвать AcceptChanges.


Не помогает.

Вот полный код:

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;
using musicBoxCode.Classes;


namespace musicBoxCode.Forms
{
    /// <summary>
    /// Summary description for Balls.
    /// </summary>
    public class Balls : System.Windows.Forms.Form
    {
        private System.Windows.Forms.DataGrid dataGrid;
        private System.Windows.Forms.DataGridTableStyle dataGridTableStyle;
        private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn_id;
        private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn_name;
        private System.Windows.Forms.Button button1;
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.Container components = null;

        private DataSet ds;

        public Balls()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();

            //
            // TODO: Add any constructor code after InitializeComponent call
            //
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose( bool disposing )
        {
            if( disposing )
            {
                if(components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose( disposing );
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.dataGrid = new System.Windows.Forms.DataGrid();
            this.dataGridTableStyle = new System.Windows.Forms.DataGridTableStyle();
            this.dataGridTextBoxColumn_id = new System.Windows.Forms.DataGridTextBoxColumn();
            this.dataGridTextBoxColumn_name = new System.Windows.Forms.DataGridTextBoxColumn();
            this.button1 = new System.Windows.Forms.Button();
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).BeginInit();
            this.SuspendLayout();
            // 
            // dataGrid
            // 
            this.dataGrid.DataMember = "";
            this.dataGrid.Dock = System.Windows.Forms.DockStyle.Top;
            this.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGrid.Name = "dataGrid";
            this.dataGrid.Size = new System.Drawing.Size(242, 200);
            this.dataGrid.TabIndex = 0;
            this.dataGrid.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
                                                                                                 this.dataGridTableStyle});
            this.dataGrid.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid_Navigate);
            // 
            // dataGridTableStyle
            // 
            this.dataGridTableStyle.AlternatingBackColor = System.Drawing.Color.White;
            this.dataGridTableStyle.BackColor = System.Drawing.Color.LightYellow;
            this.dataGridTableStyle.DataGrid = this.dataGrid;
            this.dataGridTableStyle.ForeColor = System.Drawing.Color.Navy;
            this.dataGridTableStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
                                                                                                                 this.dataGridTextBoxColumn_id,
                                                                                                                 this.dataGridTextBoxColumn_name});
            this.dataGridTableStyle.HeaderFont = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204)));
            this.dataGridTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText;
            this.dataGridTableStyle.MappingName = "Balls";
            // 
            // dataGridTextBoxColumn_id
            // 
            this.dataGridTextBoxColumn_id.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
            this.dataGridTextBoxColumn_id.Format = "";
            this.dataGridTextBoxColumn_id.FormatInfo = null;
            this.dataGridTextBoxColumn_id.HeaderText = "Код";
            this.dataGridTextBoxColumn_id.MappingName = "ball_id";
            this.dataGridTextBoxColumn_id.Width = 40;
            // 
            // dataGridTextBoxColumn_name
            // 
            this.dataGridTextBoxColumn_name.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
            this.dataGridTextBoxColumn_name.Format = "";
            this.dataGridTextBoxColumn_name.FormatInfo = null;
            this.dataGridTextBoxColumn_name.HeaderText = "Наименование";
            this.dataGridTextBoxColumn_name.MappingName = "ball_name";
            this.dataGridTextBoxColumn_name.Width = 125;
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(160, 208);
            this.button1.Name = "button1";
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Balls
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(242, 244);
            this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.button1,
                                                                          this.dataGrid});
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.Name = "Balls";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
            this.Text = "Справочник оценок";
            this.Load += new System.EventHandler(this.Balls_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).EndInit();
            this.ResumeLayout(false);

        }
        #endregion

        private void Balls_Load(object sender, System.EventArgs e)
        {
            Config cfg = Config.Instance;
            string connectionString = cfg.connectionString;
            OleDbConnection conn = new OleDbConnection(connectionString);
            conn.Open();

            OleDbDataAdapter adapter = new OleDbDataAdapter("select * from Balls", conn);
            ds = new DataSet();            
            
            adapter.Fill(ds, "Balls");
            dataGrid.SetDataBinding(ds, "Balls");

            
        }

        private void dataGrid_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
        {
        
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            ds.AcceptChanges();
        }
    }
}
... <<Слушаю Van Halen — One Foot Out The Door >>
Re[4]: Вывести данные на DataGrid из кода
От: DemAS http://demas.me
Дата: 18.03.03 16:12
Оценка:
Здравствуйте, SCS, Вы писали:

SCS>естест-но, команды на INSERT, UPDATE и DELETE должны быть построены или в дизайнере или через OleDbCommandBuilder


Как ?
... <<Слушаю Van Halen — One Foot Out The Door >>
Re[5]: Вывести данные на DataGrid из кода
От: SCS  
Дата: 18.03.03 16:20
Оценка: 6 (1)
Здравствуйте, DemAS, Вы писали:

DAS>Здравствуйте, SCS, Вы писали:


SCS>>естест-но, команды на INSERT, UPDATE и DELETE должны быть построены или в дизайнере или через OleDbCommandBuilder


DAS> Как ?

© MSDN

public DataSet SelectOleDbSrvRows(DataSet myDataSet,string myConnection,string mySelectQuery,string myTableName) 
{
    OleDbConnection myConn = new OleDbConnection(myConnection);
    OleDbDataAdapter myDataAdapter = new OleDbDataAdapter();
    myDataAdapter.SelectCommand = new OleDbCommand(mySelectQuery, myConn);
    OleDbCommandBuilder custCB = new OleDbCommandBuilder(myDataAdapter);

    myConn.Open();

    DataSet custDS = new DataSet();
    myDataAdapter.Fill(custDS, "Customers");

    //code to modify data in dataset here

    //Without the OleDbCommandBuilder this line would fail
    myDataAdapter.Update(custDS, "Customers");

    myConn.Close();

    return custDS;
 }

SCS
Re[6]: Вывести данные на DataGrid из кода
От: DemAS http://demas.me
Дата: 19.03.03 11:24
Оценка:
Здравствуйте, SCS, Вы писали:

Спасибо. Ты мне очень помог.

Есть еще один вопрос: а когда лучше делать этот update ?

На закрытие формы — довольно опасно, вдруг эл-во отключат и данные потреяются.
Вешать на таймер — тоже плохое решение.
Хорошо бы поймать событие — изменение данных в гриде, что-то типа AfterDataChange. Можно так сделать ?
... <<Слушаю Van Halen — Ain't Talkin' 'Bout Love >>
Re[7]: Вывести данные на DataGrid из кода
От: SCS  
Дата: 19.03.03 11:35
Оценка:
Здравствуйте, DemAS, Вы писали:

DAS> Хорошо бы поймать событие — изменение данных в гриде, что-то типа AfterDataChange. Можно так сделать ?

если по событию, то можно еще использовать DataTable.RowChanged
SCS
Re[8]: Вывести данные на DataGrid из кода
От: DemAS http://demas.me
Дата: 19.03.03 11:47
Оценка:
Здравствуйте, SCS, Вы писали:


SCS>если по событию, то можно еще использовать DataTable.RowChanged


Как я понимаю это событие будет вызываться и когда я просто перемещаюсь по набору данных не меняя его. Это так ?
Есди да, то получается я буду делать много лишних update(), что как я понимаю плохо ?
... <<Слушаю Van Halen — Ain't Talkin' 'Bout Love >>
Re[9]: Вывести данные на DataGrid из кода
От: AnSa Россия  
Дата: 19.03.03 12:06
Оценка: 4 (1)
Здравствуйте, DemAS, Вы писали:

DAS>Здравствуйте, SCS, Вы писали:


DAS>

SCS>>если по событию, то можно еще использовать DataTable.RowChanged

DAS> Как я понимаю это событие будет вызываться и когда я просто перемещаюсь по набору данных не меняя его. Это так ?

DAS> Есди да, то получается я буду делать много лишних update(), что как я понимаю плохо ?

Update, Insert, Delete будут вызываться только в случае если есть изменения.
Re[9]: Вывести данные на DataGrid из кода
От: SCS  
Дата: 19.03.03 12:10
Оценка: 4 (1)
Здравствуйте, DemAS, Вы писали:

DAS> Как я понимаю это событие будет вызываться и когда я просто перемещаюсь по набору данных не меняя его. Это так ?

DAS> Есди да, то получается я буду делать много лишних update(), что как я понимаю плохо ?
DataTable.RowChanged и DataTable.RowDeleted возникают только в случаях (DataRowAction)
Add      добавление новой записи в таблицу
Change   изменение полей записи
Delete   удаление записи
Commit   сработал AcceptChanges
Rollback сработал RejectChanges

т.е. это реальное изменение данных, и как правильно заметил AnSa, при update учитываются только изменения
SCS
Re[5]: Вывести данные на DataGrid из кода
От: nicknaliv  
Дата: 19.03.03 13:45
Оценка:
Здравствуйте, DemAS, Вы писали:

DAS>Здравствуйте, Alex Medvedev, Вы писали:


AM>>Необходимо вызвать AcceptChanges.


DAS> Не помогает.


DAS> Вот полный код:


DAS>
DAS>using System;
DAS>using System.Drawing;
DAS>using System.Collections;
DAS>using System.ComponentModel;
DAS>using System.Windows.Forms;
DAS>using System.Data;
DAS>using System.Data.OleDb;
DAS>using musicBoxCode.Classes;

DAS>
DAS>namespace musicBoxCode.Forms
DAS>{
DAS>    /// <summary>
DAS>    /// Summary description for Balls.
DAS>    /// </summary>
DAS>    public class Balls : System.Windows.Forms.Form
DAS>    {
DAS>        private System.Windows.Forms.DataGrid dataGrid;
DAS>        private System.Windows.Forms.DataGridTableStyle dataGridTableStyle;
DAS>        private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn_id;
DAS>        private System.Windows.Forms.DataGridTextBoxColumn dataGridTextBoxColumn_name;
DAS>        private System.Windows.Forms.Button button1;
DAS>        /// <summary>
DAS>        /// Required designer variable.
DAS>        /// </summary>
DAS>        private System.ComponentModel.Container components = null;

DAS>        private DataSet ds;

DAS>        public Balls()
DAS>        {
DAS>            //
DAS>            // Required for Windows Form Designer support
DAS>            //
DAS>            InitializeComponent();

DAS>            //
DAS>            // TODO: Add any constructor code after InitializeComponent call
DAS>            //
DAS>        }

DAS>        /// <summary>
DAS>        /// Clean up any resources being used.
DAS>        /// </summary>
DAS>        protected override void Dispose( bool disposing )
DAS>        {
DAS>            if( disposing )
DAS>            {
DAS>                if(components != null)
DAS>                {
DAS>                    components.Dispose();
DAS>                }
DAS>            }
DAS>            base.Dispose( disposing );
DAS>        }

DAS>        #region Windows Form Designer generated code
DAS>        /// <summary>
DAS>        /// Required method for Designer support - do not modify
DAS>        /// the contents of this method with the code editor.
DAS>        /// </summary>
DAS>        private void InitializeComponent()
DAS>        {
DAS>            this.dataGrid = new System.Windows.Forms.DataGrid();
DAS>            this.dataGridTableStyle = new System.Windows.Forms.DataGridTableStyle();
DAS>            this.dataGridTextBoxColumn_id = new System.Windows.Forms.DataGridTextBoxColumn();
DAS>            this.dataGridTextBoxColumn_name = new System.Windows.Forms.DataGridTextBoxColumn();
DAS>            this.button1 = new System.Windows.Forms.Button();
DAS>            ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).BeginInit();
DAS>            this.SuspendLayout();
DAS>            // 
DAS>            // dataGrid
DAS>            // 
DAS>            this.dataGrid.DataMember = "";
DAS>            this.dataGrid.Dock = System.Windows.Forms.DockStyle.Top;
DAS>            this.dataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
DAS>            this.dataGrid.Name = "dataGrid";
DAS>            this.dataGrid.Size = new System.Drawing.Size(242, 200);
DAS>            this.dataGrid.TabIndex = 0;
DAS>            this.dataGrid.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] {
DAS>                                                                                                 this.dataGridTableStyle});
DAS>            this.dataGrid.Navigate += new System.Windows.Forms.NavigateEventHandler(this.dataGrid_Navigate);
DAS>            // 
DAS>            // dataGridTableStyle
DAS>            // 
DAS>            this.dataGridTableStyle.AlternatingBackColor = System.Drawing.Color.White;
DAS>            this.dataGridTableStyle.BackColor = System.Drawing.Color.LightYellow;
DAS>            this.dataGridTableStyle.DataGrid = this.dataGrid;
DAS>            this.dataGridTableStyle.ForeColor = System.Drawing.Color.Navy;
DAS>            this.dataGridTableStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] {
DAS>                                                                                                                 this.dataGridTextBoxColumn_id,
DAS>                                                                                                                 this.dataGridTextBoxColumn_name});
DAS>            this.dataGridTableStyle.HeaderFont = new System.Drawing.Font("Arial", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(204)));
DAS>            this.dataGridTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText;
DAS>            this.dataGridTableStyle.MappingName = "Balls";
DAS>            // 
DAS>            // dataGridTextBoxColumn_id
DAS>            // 
DAS>            this.dataGridTextBoxColumn_id.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
DAS>            this.dataGridTextBoxColumn_id.Format = "";
DAS>            this.dataGridTextBoxColumn_id.FormatInfo = null;
DAS>            this.dataGridTextBoxColumn_id.HeaderText = "Код";
DAS>            this.dataGridTextBoxColumn_id.MappingName = "ball_id";
DAS>            this.dataGridTextBoxColumn_id.Width = 40;
DAS>            // 
DAS>            // dataGridTextBoxColumn_name
DAS>            // 
DAS>            this.dataGridTextBoxColumn_name.Alignment = System.Windows.Forms.HorizontalAlignment.Center;
DAS>            this.dataGridTextBoxColumn_name.Format = "";
DAS>            this.dataGridTextBoxColumn_name.FormatInfo = null;
DAS>            this.dataGridTextBoxColumn_name.HeaderText = "Наименование";
DAS>            this.dataGridTextBoxColumn_name.MappingName = "ball_name";
DAS>            this.dataGridTextBoxColumn_name.Width = 125;
DAS>            // 
DAS>            // button1
DAS>            // 
DAS>            this.button1.Location = new System.Drawing.Point(160, 208);
DAS>            this.button1.Name = "button1";
DAS>            this.button1.TabIndex = 1;
DAS>            this.button1.Text = "button1";
DAS>            this.button1.Click += new System.EventHandler(this.button1_Click);
DAS>            // 
DAS>            // Balls
DAS>            // 
DAS>            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
DAS>            this.ClientSize = new System.Drawing.Size(242, 244);
DAS>            this.Controls.AddRange(new System.Windows.Forms.Control[] {
DAS>                                                                          this.button1,
DAS>                                                                          this.dataGrid});
DAS>            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
DAS>            this.Name = "Balls";
DAS>            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
DAS>            this.Text = "Справочник оценок";
DAS>            this.Load += new System.EventHandler(this.Balls_Load);
DAS>            ((System.ComponentModel.ISupportInitialize)(this.dataGrid)).EndInit();
DAS>            this.ResumeLayout(false);

DAS>        }
DAS>        #endregion

DAS>        private void Balls_Load(object sender, System.EventArgs e)
DAS>        {
DAS>            Config cfg = Config.Instance;
DAS>            string connectionString = cfg.connectionString;
DAS>            OleDbConnection conn = new OleDbConnection(connectionString);
DAS>            conn.Open();

DAS>            OleDbDataAdapter adapter = new OleDbDataAdapter("select * from Balls", conn);
DAS>            ds = new DataSet();            
DAS>            
DAS>            adapter.Fill(ds, "Balls");
DAS>            dataGrid.SetDataBinding(ds, "Balls");

DAS>            
DAS>        }

DAS>        private void dataGrid_Navigate(object sender, System.Windows.Forms.NavigateEventArgs ne)
DAS>        {
DAS>        
DAS>        }

DAS>        private void button1_Click(object sender, System.EventArgs e)
DAS>        {
DAS>            ds.AcceptChanges();
DAS>        }
DAS>    }
DAS>}

DAS>


DAS>


DAS>


попробуй так
private void button1_Click(object sender, System.EventArgs e)
{
adapter.Update(ds)
ds.AcceptChanges();
}

при этом у адаптера должны быть определены InsertCommand, UpdateCommand, DeleteCommand
их можно построить с помощь класса CommandBuilder
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.