0

First of all, what is a "data source", the kind that can be attached to a "DataGridView", what are they used for, and how can I use one?

3
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by Momerath
1

DataSource is a property of some controls (like DataGridView) which is used for binding data to these Controls.

The best would be to look an example:

public partial class Form1 : Form
    {
        DataGridView dgv;
        DataTable table;
        BindingSource bs;
        public Form1()
        {
            InitializeComponent();
            
            dgv = new DataGridView();
            dgv.Location = new Point(20, 20);

            //this will always create a new row in the end of dgv:
            //when user will do insertion into new row of dgv, 
            //data will be automatically transfered to dataTable as well!
            dgv.AllowUserToAddRows = true;
            this.Controls.Add(dgv);
            CreatingDataSource();
        }

        private void CreatingDataSource()
        {
            table = new DataTable("myTable");
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Name", typeof(string));
            //get some example data:
            table = GetData(table);
            //bind table to binding source:
            bs = new BindingSource(table, null);
            //bind binding source to dgv:
            dgv.DataSource = bs;
        }

        private DataTable GetData(DataTable table)
        {
            //my example data (I will add 2 rows):
            DataRow dr;
            for (int i = 1; i < 3; i++)
            {
                dr = table.NewRow();
                dr["Id"] = i;
                dr["Name"] = "name " + i;
                table.Rows.Add(dr);
            }
            return table;
        }
    }

Hope it helps,
Mitja

Votes + Comments
Good explanation!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.