简体   繁体   English

使用C Sharp进行gridview编程

[英]gridview programming using c sharp

我如何使用c#代码在gridview中获取多个选定的行以及我必须以另一种形式显示的选定行也具有gridview

public partial class WindowForm: Form
    {
        private DataTable dataTable = new DataTable();
       //This will contain all the selected rows.
        private List<DataGridViewRow> selectedRows = new List<DataGridViewRow>();

        public WindowForm()
        {
            InitializeComponent();
            dataTable .Columns.Add("Column1");
            dataTable .Columns.Add("Column2");
            dataTable .Columns.Add("Column3");
            for (int i = 0; i < 30; i++)
            {
                dataTable .Rows.Add(i, "Row" + i.ToString(), "Item" + i.ToString());
            }
            dataGridView1.DataSource = dataTable ;
            //This will select full row of a grid
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //This will allow multi selection
            dataGridView1.MultiSelect = true;

            dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
            dataGridView1.CellBeginEdit += new DataGridViewCellCancelEventHandler(dataGridView1_CellBeginEdit);
        }

        void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            PerformSelection(dataGridView1, selectedRows);
        }

        void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {
            if (selectedRows.Contains(dataGridView1.CurrentRow))
            {
                selectedRows.Remove(dataGridView1.CurrentRow);
            }
            else
            {
                selectedRows.Add(dataGridView1.CurrentRow);
            }
            PerformSelection(this.dataGridView1, selectedRows);

        }

        private void PerformSelection(DataGridView dgv, List<DataGridViewRow> selectedRowsCollection)
        {  
            foreach (DataGridViewRow dgvRow in dgv.Rows)
            {
                if (selectedRowsCollection.Contains(dgvRow))
                {
                    dgvRow.Selected = true;
                }
                else
                {
                    dgvRow.Selected = false;
                }
            }
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM