datagridview-save-restore-scroll-position ソースコード全文

DataGridView_Save_Restore_Scroll_Position.slnx

DataGridView_Save_Restore_Scroll_Position.slnx
<Solution>
<Project Path="DataGridView_Save_Restore_Scroll_Position/DataGridView_Save_Restore_Scroll_Position.csproj" />
</Solution>

DataGridView_Save_Restore_Scroll_Position/DataGridView_Save_Restore_Scroll_Position.csproj

DataGridView_Save_Restore_Scroll_Position.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
</Project>

DataGridView_Save_Restore_Scroll_Position/DataGridView_Save_Restore_Scroll_Position.csproj.user

DataGridView_Save_Restore_Scroll_Position.csproj.user
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Compile Update="Form1.cs">
<SubType>Form</SubType>
</Compile>
</ItemGroup>
</Project>

DataGridView_Save_Restore_Scroll_Position/Form1.cs

Form1.cs
using System.Data;
namespace DataGridView_Save_Restore_Scroll_Position
{
public partial class Form1 : Form
{
private DataTable _dataTable = new DataTable();
// スクロール位置を記憶するための変数
private int _savedVerticalRowIndex = -1;
private int _savedHorizontalOffset = 0;
public Form1()
{
InitializeComponent();
InitializeDataGridView();
btnSaveScroll.Click += btnSaveScroll_Click;
btnRestoreScroll.Click += btnRestoreScroll_Click;
}
private void InitializeDataGridView()
{
// テスト用に大量の列と行を作成(100行×20列)
for (int i = 1; i <= 20; i++)
{
_dataTable.Columns.Add($"Column_{i}", typeof(string));
}
for (int i = 1; i <= 100; i++)
{
DataRow row = _dataTable.NewRow();
for (int j = 1; j <= 20; j++)
{
row[$"Column_{j}"] = $"R{i}-C{j}";
}
_dataTable.Rows.Add(row);
}
dataGridView1.DataSource = _dataTable;
}
/// <summary>
/// 「位置を保存」ボタンのクリックイベント
/// </summary>
private void btnSaveScroll_Click(object? sender, EventArgs e)
{
// 1. 現在画面の最上部に表示されている行インデックスを保存
_savedVerticalRowIndex = dataGridView1.FirstDisplayedScrollingRowIndex;
// 2. 現在の水平スクロールのピクセルオフセット値を保存
_savedHorizontalOffset = dataGridView1.HorizontalScrollingOffset;
MessageBox.Show($"現在のスクロール位置を保存しました。\n垂直行: {_savedVerticalRowIndex}\n水平オフセット: {_savedHorizontalOffset}px");
}
/// <summary>
/// 「位置を復元」ボタンのクリックイベント
/// </summary>
private void btnRestoreScroll_Click(object? sender, EventArgs e)
{
// まだ一度も保存されていない場合は処理しない
if (_savedVerticalRowIndex == -1)
{
MessageBox.Show("先にスクロール位置を保存してください。");
return;
}
// --- 垂直スクロール(上下)の復元 ---
// 記憶した行インデックスが現時点の総行数を超えていないか安全確認を行う
if (_savedVerticalRowIndex >= 0 && _savedVerticalRowIndex < dataGridView1.RowCount)
{
try
{
dataGridView1.FirstDisplayedScrollingRowIndex = _savedVerticalRowIndex;
}
catch (InvalidOperationException)
{
// セルが非表示などの理由でスクロールできない場合の例外対策
}
}
// --- 水平スクロール(左右)の復元 ---
// 水平オフセットを代入して復元(範囲外の値が指定された場合は自動で最大値に丸められます)
if (_savedHorizontalOffset >= 0)
{
dataGridView1.HorizontalScrollingOffset = _savedHorizontalOffset;
}
}
}
}

DataGridView_Save_Restore_Scroll_Position/Form1.Designer.cs

Form1.Designer.cs
namespace DataGridView_Save_Restore_Scroll_Position
{
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()
{
tableLayoutPanel1 = new TableLayoutPanel();
tableLayoutPanel2 = new TableLayoutPanel();
btnSaveScroll = new Button();
btnRestoreScroll = new Button();
dataGridView1 = new DataGridView();
tableLayoutPanel1.SuspendLayout();
tableLayoutPanel2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// tableLayoutPanel1
//
tableLayoutPanel1.ColumnCount = 1;
tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel1.Controls.Add(tableLayoutPanel2, 0, 1);
tableLayoutPanel1.Controls.Add(dataGridView1, 0, 0);
tableLayoutPanel1.Dock = DockStyle.Fill;
tableLayoutPanel1.Location = new Point(0, 0);
tableLayoutPanel1.Name = "tableLayoutPanel1";
tableLayoutPanel1.RowCount = 2;
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 86F));
tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 14F));
tableLayoutPanel1.Size = new Size(800, 450);
tableLayoutPanel1.TabIndex = 0;
//
// tableLayoutPanel2
//
tableLayoutPanel2.ColumnCount = 2;
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Controls.Add(btnSaveScroll, 0, 0);
tableLayoutPanel2.Controls.Add(btnRestoreScroll, 1, 0);
tableLayoutPanel2.Dock = DockStyle.Fill;
tableLayoutPanel2.Location = new Point(3, 390);
tableLayoutPanel2.Name = "tableLayoutPanel2";
tableLayoutPanel2.RowCount = 1;
tableLayoutPanel2.RowStyles.Add(new RowStyle(SizeType.Percent, 50F));
tableLayoutPanel2.Size = new Size(794, 57);
tableLayoutPanel2.TabIndex = 0;
//
// btnSaveScroll
//
btnSaveScroll.Dock = DockStyle.Fill;
btnSaveScroll.Location = new Point(3, 3);
btnSaveScroll.Name = "btnSaveScroll";
btnSaveScroll.Size = new Size(391, 51);
btnSaveScroll.TabIndex = 0;
btnSaveScroll.Text = "スクロール位置の保存";
btnSaveScroll.UseVisualStyleBackColor = true;
//
// btnRestoreScroll
//
btnRestoreScroll.Dock = DockStyle.Fill;
btnRestoreScroll.Location = new Point(400, 3);
btnRestoreScroll.Name = "btnRestoreScroll";
btnRestoreScroll.Size = new Size(391, 51);
btnRestoreScroll.TabIndex = 1;
btnRestoreScroll.Text = "スクロール位置の復元";
btnRestoreScroll.UseVisualStyleBackColor = true;
//
// dataGridView1
//
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.Dock = DockStyle.Fill;
dataGridView1.Location = new Point(3, 3);
dataGridView1.Name = "dataGridView1";
dataGridView1.RowHeadersWidth = 62;
dataGridView1.Size = new Size(794, 381);
dataGridView1.TabIndex = 1;
//
// Form1
//
AutoScaleDimensions = new SizeF(10F, 25F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 450);
Controls.Add(tableLayoutPanel1);
Name = "Form1";
Text = "Form1";
tableLayoutPanel1.ResumeLayout(false);
tableLayoutPanel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
}
#endregion
private TableLayoutPanel tableLayoutPanel1;
private TableLayoutPanel tableLayoutPanel2;
private Button btnSaveScroll;
private Button btnRestoreScroll;
private DataGridView dataGridView1;
}
}

DataGridView_Save_Restore_Scroll_Position/Form1.resx

Form1.resx
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

DataGridView_Save_Restore_Scroll_Position/Program.cs

Program.cs
namespace DataGridView_Save_Restore_Scroll_Position
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}