Form DataGridView BindingSource to bind in several ways

 

This link: https://blog.csdn.net/qq_15138169/article/details/83341076

In developing the WinForm, ListView and DataGridView application scenarios are compared beginner bundled data are used the most simplest way to achieve

  1.  
  2. private void NormalAdd()
  3. {
  4.      dataGridView1.Rows.Clear();
  5.      for (int i = 0; i < 10; ++i)
  6.      {
  7.          int index = dataGridView1.Rows.Add();
  8.          dataGridView1.Rows[index].Cells[0].Value = i+"elem1";
  9.          dataGridView1.Rows[index].Cells[1].Value = i+"elem2";
  10.          dataGridView1.Rows[index].Cells[2].Value = i+"elem3";

dataGridView1.Rows[index].Cells[2].Value = i+"elem4";

 

 

 

The above method is the most intuitive, but Microsoft also offers several other more elegant way to bind some of the data is accomplished by BindingSource, BindingSource see the name to know Gansha use the.

 

public List<ItemBean> list = new List<ItemBean>();

private void dataList()

{

    for (int i = 0; i < 10; ++i)

    {

        ItemBean sin = new ItemBean ();

        item.postion = i.ToString();

        item.item1 = "Listitem1-" + i;

        item.item2 = "Listitem2-" + i;

        item.item3 = "Listitem3-" + i;

        list.Add(item);

    }

    bindingSource1.DataSource = list;

    Binding // DataGridView column name and object members

    dataGridView1.Columns["Column1"].DataPropertyName = "postion";

    dataGridView1.Columns["Column2"].DataPropertyName = "item1";

    dataGridView1.Columns["Column3"].DataPropertyName = "item2";

    dataGridView1.Columns["Column4"].DataPropertyName = "item3";

}

public class ItemBean

{

    public string postion { get; set; }

    public string item1 { get; set; }

    public string item2 { get; set; }

    public string item3 { get; set; }

}

This is the way to achieve data sources bind List

 

public DataTable dt = new DataTable("ITEMBEAN");

private void dataTable()

{

    dt.Columns.Add("POS", typeof(string));

    dt.Columns.Add("ITEM1", typeof(string));

    dt.Columns.Add("ITEM2", typeof(string));

    dt.Columns.Add("ITEM3", typeof(string));

    for (int i = 0; i < 10; ++i)

    {

        DataRow dr = dt.NewRow();

        dr[0] = i.ToString();

        dr [1] = i.ToString () + "_Table unit 1";

        dr [2] = i.ToString () + "_Table unit 2";

        dr [3] = i.ToString () + "_Table unit 3";

        dt.Rows.Add(dr);

    }

    bindingSource1.DataSource = dt;

    dataGridView1.Columns["Column1"].DataPropertyName = "POS";

    dataGridView1.Columns["Column2"].DataPropertyName = "ITEM1";

    dataGridView1.Columns["Column3"].DataPropertyName = "ITEM2";

    dataGridView1.Columns["Column4"].DataPropertyName = "ITEM3";

}

This is the way DataTable, there are several other, we can go to try, both in the practical application of the project should be some more scenes.



Guess you like

Origin www.cnblogs.com/wfy680/p/12004514.html
Recommended