移动数据源记录时,DataGridView选择会发生更改。 [英] DataGridView selection changes when moving data source records.

查看:47
本文介绍了移动数据源记录时,DataGridView选择会发生更改。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

移动行时,我遇到使用自定义BindingList数据源的DataGridView时遇到问题。 我希望在移动行时选择当前选定的行(例如,当数据集按列排序并且值更改时)。 我将
提取到下面的示例应用程序。

I'm having trouble with a DataGridView with a custom BindingList data source when rows are moved.  I want to keep the currently selected row selected when rows are moved (e.g. when the data set is sorted on a column and a value changes).  I've distilled it down to a sample application included below.

选择标记为"SELECT"的单元格。 每次按"按钮1"时,行索引8将移动到行索引1。  "SELECT"是指"SELECT"。单元格保持选中状态,直到您按下"button1"按钮。第7次。

Select the cell marked "SELECT".  Every time you press "button1", row index 8 will be moved to row index 1.  The "SELECT" cell remains selected until you press "button1" for the 7th time.

注意"SELECT"是怎样的。不再选择该行。 为什么这样做以及如何防止所选行在这种情况下发生变化?

Notice how the "SELECT" row is no longer selected.  Why is this and what can I do to prevent the selected row from changing in this situation?

谢谢,

Todd

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace SampleApplication
{
	public partial class Form1 : Form
	{
		private BindList list = new BindList();

		public Form1()
		{
			InitializeComponent();
			list.Add(new Item("0", "zero"));
			list.Add(new Item("SELECT", "one"));
			list.Add(new Item("2", "two"));
			list.Add(new Item("3", "three"));
			list.Add(new Item("4", "four"));
			list.Add(new Item("5", "five"));
			list.Add(new Item("6", "six"));
			list.Add(new Item("7", "seven"));
			list.Add(new Item("8", "eight"));
			list.Add(new Item("9", "nine"));

			bindingSource1.DataSource = list;
		}

		private void button1_Click(object sender, EventArgs e)
		{
			list.Move(8, 1);
		}

		public class BindList : BindingList<Item>
		{
			private void FireEvent1(ListChangedEventArgs args)
			{
				OnListChanged(args);
			}

			public void Move(int origin, int desination)
			{
				Move1(origin, desination);
				FireEvent1(new ListChangedEventArgs(ListChangedType.ItemMoved, origin, desination));
			}

			private void Move1(int a, int b)
			{
				Item i = this[a];

				RemoveAt(a);
				Insert(b, i);
			}
		}

		public class Item
		{
			private string id;
			private string name;

			public string Id
			{
				get
				{
					return id;
				}
				set
				{
					id = value;
				}
			}

			public string Name
			{
				get
				{
					return name;

				}
				set
				{
					name = value;
				}
			}

			public Item(string id, string name)
			{
				this.id = id;
				this.name = name;
			}

			public override string ToString()
			{
				return id + " " + name;
			}
		}
	}
}

namespace SampleApplication
{
	partial class Form1
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			this.dataGridView1 = new System.Windows.Forms.DataGridView();
			this.idDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
			this.nameDataGridViewTextBoxColumn = new System.Windows.Forms.DataGridViewTextBoxColumn();
			this.bindingSource1 = new System.Windows.Forms.BindingSource(this.components);
			this.button1 = new System.Windows.Forms.Button();
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).BeginInit();
			this.SuspendLayout();
			// 
			// dataGridView1
			// 
			this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
            | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
			this.dataGridView1.AutoGenerateColumns = false;
			this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
            this.idDataGridViewTextBoxColumn,
            this.nameDataGridViewTextBoxColumn});
			this.dataGridView1.DataSource = this.bindingSource1;
			this.dataGridView1.Location = new System.Drawing.Point(12, 12);
			this.dataGridView1.Name = "dataGridView1";
			this.dataGridView1.Size = new System.Drawing.Size(271, 295);
			this.dataGridView1.TabIndex = 0;
			// 
			// idDataGridViewTextBoxColumn
			// 
			this.idDataGridViewTextBoxColumn.DataPropertyName = "Id";
			this.idDataGridViewTextBoxColumn.HeaderText = "Id";
			this.idDataGridViewTextBoxColumn.Name = "idDataGridViewTextBoxColumn";
			// 
			// nameDataGridViewTextBoxColumn
			// 
			this.nameDataGridViewTextBoxColumn.DataPropertyName = "Name";
			this.nameDataGridViewTextBoxColumn.HeaderText = "Name";
			this.nameDataGridViewTextBoxColumn.Name = "nameDataGridViewTextBoxColumn";
			// 
			// bindingSource1
			// 
			this.bindingSource1.DataSource = typeof(SampleApplication.Form1.Item);
			// 
			// button1
			// 
			this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.button1.Location = new System.Drawing.Point(289, 12);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(75, 23);
			this.button1.TabIndex = 1;
			this.button1.Text = "button1";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.Click += new System.EventHandler(this.button1_Click);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(376, 319);
			this.Controls.Add(this.button1);
			this.Controls.Add(this.dataGridView1);
			this.Name = "Form1";
			this.Text = "Form1";
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.bindingSource1)).EndInit();
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.DataGridView dataGridView1;
		private System.Windows.Forms.BindingSource bindingSource1;
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.DataGridViewTextBoxColumn idDataGridViewTextBoxColumn;
		private System.Windows.Forms.DataGridViewTextBoxColumn nameDataGridViewTextBoxColumn;
	}
}







推荐答案

您好,

当我使用BindingSource执行此操作时,
position需要更新
。对不起,以下是VB.NET,语言扩展旨在与DataGridView一起工作,数据源是BindingSource来上下移动行。也许这可以通过使VB.NET适应C Sharp来帮助你。

When I do this with a BindingSource the position needs updating. Sorry that the following is VB.NET, the language extensions are designed to work with a DataGridView were the data source is a BindingSource to move rows up and down. Perhaps this can asssist you by adapting VB.NET to C Sharp.

变量bsData是一个BindingSource的示例,其中DataTable作为DataSource

Example where the variable bsData is a BindingSource with a DataTable as the DataSource

DataGridView1.MoveRowUp(bsData)

语言扩展程序

<System.Diagnostics.DebuggerStepThrough()> _<Runtime.CompilerServices.Extension()> _Public Sub MoveRowUp(ByVal sender As DataGridView, ByVal bs As BindingSource)    If Not String.IsNullOrWhiteSpace(bs.Sort) Then        bs.Sort = ""    End If    Dim CurrentColumnIndex As Integer = sender.CurrentCell.ColumnIndex    Dim NewIndex As Int32 = CInt(IIf(bs.Position = 0, 0, bs.Position - 1))    Dim dt = CType(bs.DataSource, DataTable)    Dim RowToMove As DataRow = DirectCast(bs.Current, DataRowView).Row    Dim NewRow As DataRow = dt.NewRow    NewRow.ItemArray = RowToMove.ItemArray    dt.Rows.RemoveAt(bs.Position)    dt.Rows.InsertAt(NewRow, NewIndex)    bs.Position = NewIndex    sender.CurrentCell = sender(CurrentColumnIndex, NewIndex)End Sub<System.Diagnostics.DebuggerStepThrough()> _<Runtime.CompilerServices.Extension()> _Public Sub MoveRowDown(ByVal sender As DataGridView, ByVal bs As BindingSource)    If Not String.IsNullOrWhiteSpace(bs.Sort) Then        bs.Sort = ""    End If    Dim CurrentColumnIndex As Integer = sender.CurrentCell.ColumnIndex    Dim UpperLimit As Int32 = bs.Count - 1    Dim NewIndex As Int32 = CInt(IIf(bs.Position + 1 >= UpperLimit, UpperLimit, bs.Position + 1))    Dim dt = CType(bs.DataSource, DataTable)    Dim RowToMove As DataRow = DirectCast(bs.Current, DataRowView).Row    Dim NewRow As DataRow = dt.NewRow    NewRow.ItemArray = RowToMove.ItemArray    dt.Rows.RemoveAt(bs.Position)    dt.Rows.InsertAt(NewRow, NewIndex)    bs.Position = NewIndex    sender.CurrentCell = sender(CurrentColumnIndex, NewIndex)End Sub





这篇关于移动数据源记录时,DataGridView选择会发生更改。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆