2013年12月16日 星期一

[C#]利用BindingSource實現DataGridView 排序

  private DataTable _dt;
  private BindingSource _BindingSource;

    public Form1()
   {
            InitializeComponent();
            _dt = new DataTable();
            _BindingSource = new BindingSource();
     }


        private void Form1_Load(object sender, EventArgs e)
        {
            _dt.TableName = "TestDataTable";
            _dt.Columns.Add(new DataColumn("Sroting", typeof(int)));
            _dt.Columns.Add(new DataColumn("Name", typeof(string)));

            DataRow dr;
            for (int i = 1; i < 10; i++)
            {
                dr = _dt.NewRow();
                dr["Sroting"] = i;
                dr["Name"] = "Text" + i.ToString();
                _dt.Rows.Add(dr);

            }

        }

        private void button1_Click(object sender, EventArgs e)
        {

            _BindingSource.DataSource = _dt;
            _BindingSource.Sort = "Sroting Asc";


            dataGridView1.DataSource = null;
            dataGridView1.DataSource = _BindingSource;

        }

        private void btnUpSorting_Click(object sender, EventArgs e)
        {

            if (_BindingSource.Position == 0) {

                return;
            }


            ((DataRowView)_BindingSource[_BindingSource.Position - 1]).Row.BeginEdit();
            ((DataRowView)_BindingSource[_BindingSource.Position - 1]).Row["Sroting"] = (int)((DataRowView)_BindingSource[_BindingSource.Position - 1]).Row["Sroting"] + 1;
            ((DataRowView)_BindingSource[_BindingSource.Position - 1]).Row.EndEdit();

            ((DataRowView)_BindingSource[_BindingSource.Position]).Row.BeginEdit();
            ((DataRowView)_BindingSource[_BindingSource.Position]).Row["Sroting"] = (int)((DataRowView)_BindingSource[_BindingSource.Position]).Row["Sroting"] - 1;
            ((DataRowView)_BindingSource[_BindingSource.Position]).Row.EndEdit();

        }

        private void btnDownSorting_Click(object sender, EventArgs e)
        {
            if (_BindingSource.Position == (_dt.Rows.Count-1))
            {
                return;
            }


            ((DataRowView)_BindingSource[_BindingSource.Position + 1]).Row.BeginEdit();
            ((DataRowView)_BindingSource[_BindingSource.Position + 1]).Row["Sroting"] = (int)((DataRowView)_BindingSource[_BindingSource.Position + 1]).Row["Sroting"] - 1;
            ((DataRowView)_BindingSource[_BindingSource.Position + 1]).Row.EndEdit();

            ((DataRowView)_BindingSource[_BindingSource.Position]).Row.BeginEdit();
            ((DataRowView)_BindingSource[_BindingSource.Position]).Row["Sroting"] = (int)((DataRowView)_BindingSource[_BindingSource.Position]).Row["Sroting"] + 1;
            ((DataRowView)_BindingSource[_BindingSource.Position]).Row.EndEdit();
 
        }

執行結果:


沒有留言:

張貼留言