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?

Recommended Answers

All 2 Replies

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

commented: Good explanation! +9
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.