約 4,936,666 件
https://w.atwiki.jp/mini98/pages/31.html
DataGridにデータを代入するには、ListDataProviderを利用する。ListDataProvider#getList でList T を取得できる。 参考
https://w.atwiki.jp/lele/pages/12.html
WindowsFormのDataGridで、検索結果を表示していたんだけど、何度か検索してセルを選択したりすると「インデックスが配列の境界外です。」がでる。 調べてみると、選択セルの行が次の検索でなくなった後、他のセルを選択する時に、以前選択していたセルに対して何か処理が行われる模様。 解決法: Gridデータ変更時に、 DataGrid.CurrentRowIndex = 0 参考: http //blogs.wankuma.com/naka/archive/2005/02/06/8623.aspx http //www.dotnet247.com/247reference/msgs/26/134878.aspx
https://w.atwiki.jp/lele/pages/13.html
いろいろ方法はあると思うけど、今回やった方法をまとめます。 やること: 1.DB検索結果をDataGridに表示 2.ID列は非表示 3.一番左に行選択用のチェックボックスを表示 やったこと: <DataSet(xsd)> 1.DataSetクラスを追加し、検索結果内容+チェックボックスをxsdに登録。(テーブルエレメント名をeletblとする) チェックボックスは type="xs boolean" とする <Formデザイナ> 2.FormにデザイナでDataSetを型指定されたデータセットで1を選んで追加(データセット名をdsとする) 3.FormにデザイナでDataGridを追加し、プロパティ設定 DataSource=ds, DataMemeber=eletbl <DataGridTableStyle コレクションエディタ> 4.プロパティTableStylesの「...」ボタンクリック。「追加」→「OK」。再度プロパティTableStylesの「...」ボタンクリック 5.追加したメンバを選択し、MappingNameにeletblを設定 6.GridColumnStyleの「...」ボタンクリック <DataGridColumnStyle コレクションエディタ> 7.検索カラム数 DataGridTextBoxColumnを追加。それぞれMappingNameにカラム名を設定。 チェックボックスはDataGridBoolColumnで追加。タイトル文字もここで入れる 8.IDカラムのwidth=0 <DB検索> 9.検索のSelect句にダミーのチェックボックス列を含める。 10.結果のDataSetの中身をDataGridのDataSourceに列コピー DataGridにコピー(DataGridのスタイルを変更しないようにするため) Dim srcdt As DataTable = resultDataSet.Tables(0) Dim ds As DataSet = CType(Me.DataGrid1.DataSource, DataSet) Dim dt As DataTable = ds.Tables(0) dt.Clear() Dim dr As DataRow For Each dr In srcdt.Rows dt.ImportRow(dr) Next <チェック行の取得> Dim dt As DataTable = CType(Me.DataGrid1.DataSource, DataSet).Tables(0) Dim dr As DataRow For Each dr In dt.Rows If (dr("check列名")) Then rowsList.Add(dr) End If Next
https://w.atwiki.jp/eqtunarejp/pages/89.html
Spells Faction Venderの一覧表 Faction Ak Anon Strike Force V Bertoxxulous Chosen Brownie Rebels Camp Valor Crusaders of Veeshan Fang Breakers Ladies of the Light Zone Dragonscale Hills Hills of Shade The Steam Factory Hills of Shade Dragonscale Hills Loping Plains Dragonscale Hills Supply Normal Automated Vending Unit II Lanika Shadestepper Karri Hardrin Aring Derak Fangbreaker Seridyn Elite Ak`Akanon Supplier Mark LXXXVIII Shelsy Shadestepper Little Bo a mysterious stranger Sydria the Elder Brett of the Watch Alissa Saint Claire Rk.II Spells Faction Spellsの一覧表 Faction Ak Anon Strike Force V Bertoxxulous Chosen Brownie Rebels Camp Valor Crusaders of Veeshan Fang Breakers Ladies of the Light ENC Kindly 78 Wake of Atrophy 79 Aura of Horror 77 Runic Swirl Aura 79 Aura of Endless Glamour Ally 77 Mystifier s Aura 78 Mana Resurgence 80 Mana Resurgence Aura Durus 79 Quelling Wave 76 Mystifying Flash 80 Mind Oscillate 77 Strangling Air Irae 80 Mind Oscillate 77 Strangling Air 77 Multichromatic Assault MAG Kindly 80 Fickle Pyroclasm 77 Shock of Many 80 Mass Prime Transvergence 80 Monster Summoning VI Ally 80 Rancorous Servant 79 Burning Brimbody 78 Summon Cauldron of Many Things Irae Shock of Cineral Steel Bolt of Molten Dross Shock of Many Annihilate the Aberrant Fickle Pyroclasm,Scorching Sands Salus Revival of Aenro NEC Kindly 78 Pyre of the Lifeless 77 Putrefaction 77 Bonestitch Charm 76 Phantasmal Orb Ally 80 Splort 80 Venonscale Venom 79 Reaver s Pyre Irae Reaver s Pyre,Splort Eranon s Decay Ruinous Venin,Venonscale Venom Supplication of Blood Pyre of the Lifeless Visziaj s Pallid Haze Searing Shadow WIZ Kindly 79 Chaos Conflagration 79 Ethereal Rime 7880 Funnel of Frost,Tangleweave Energy Ally 76 Wildmagic Burst 78 Rime Snap 79 Flashflames Irae Claw of Selig Rolling Lightning Chaos Conflagration,Inizen s Fire Glacial Collapse Flashflames Rime Snap Cloudburst Bolts,Pure Wildmagic Ethereal Incineration Ethereal Rime,Pyrolure Lure of Isaz Tangleweave Energy Faction Ak Anon Strike Force V Bertoxxulous Chosen Brownie Rebels Camp Valor Crusaders of Veeshan Fang Breakers Ladies of the Light CLR Kindly 80 Blood of the Devoted 78 Hallowed Ground 77 Eleventh-Hour 79 Chromaassault Ally 76 Vow of Victory 80 Circle of Divinity 78 Promised Restoration Durus Solemn Elixir Irae Chromassault,Sermon of Admonition Divine Censure Salus Solemn Remedy Solemn Light Eleventh-Hour,Frantic Renewal DRU Kindly 76 Fernspike 78 Solarsliver 78 Survival of the Fittest 80 Preincarnation Ally 80 Nature s Burning Wrath 78 Winter s Blaze 79 Scales of the Reptile Irae Reaping Inferno Winter s Blaze Nature s Burning Wrath Equinox Brand Annihilate the Aberrant Horde of Fireants Salus Adrenaline Swell,Puravida SHM Kindly 77 Rolist s Drowse 78 Ancestral Intervention 77 Languor 80 Preincarnation Ally 78 Bite of the Brownie 76 Talisman of the Puma 79 Ward of Resurgence Durus Shade of Renewal Irae Tundra Crumble Bite of the Brownie Vengeance of Kerafyrm Pocus,Rancor of Agony Vestax s Spear of Venom Salus Gemmi s Restoration Faction Ak Anon Strike Force V Bertoxxulous Chosen Brownie Rebels Camp Valor Crusaders of Veeshan Fang Breakers Ladies of the Light BRD Kindly 78 Erradien s Psalm of Potency 79 Polyphony of Pain 80 Kaerra s Spirited Crescendo Ally 80 Aura of the Artist 80 Arcane Anthem BST Kindly 79 Growl of the Puma 78 Promised Recovery 78 Bite of the Borrower Ally 80 Harrow 80 Howl at the Moon Irae Jagged Torrent Bite of the Borrower Fever Surge Salus Daria s Mending Salve of Feldan Tempus Harrow PAL Kindly 78 Burst of Morrow 80 Righteous Fury Ally 80 Sustenance of Tunare 80 Aurora of Morrow 77 Trial for Honor Durus Trial for Honor Solemn Cleansing Irae Benediction Salus Burst of Morrow Radiant Light Solemn Touch RNG Kindly 77 Jolting Snapkicks 78 Deadfall 79 Arc of Arrows Ally 80 Aimshot Discipline 79 Summer s Viridity Irae Summer s Viridity Horde of Hornets Rimefall Bite Galvanic Ash Salus Dragonscale Aquifer Tempus Heartsting SHD Kindly 77 Assiduous Impurity 76 Soulthirst Horror 80 Last Grasp Ally 80 Umbral Skin 77 Trial for Power Durus Trial for Power Irae Touch of Kildrukaun Touch of the Soulbleeder Rotmarrow Spear Bond of the Blackwater Blood of the Blackwater Blackwater Bite Faction Ak Anon Strike Force V Bertoxxulous Chosen Brownie Rebels Camp Valor Crusaders of Veeshan Fang Breakers Ladies of the Light BSK Kindly 80 Battle Frenzy Ally 79 Decimator s Volley Tempus Temple Strike Decimator s Volley Tendon Sever Third Wind MNK Kindly 80 Delay Death Ally 80 Wheel Fists Tempus Delay Death Wheel of Fists Third Wind Crystalpalm Discipline ROG Kindly 80 Fadelure Ally 80 Swiftblade Tempus Docent of Toxicity Third Wind Blinding Flare Pinpoint Weaknesses WAR Kindly 80 Knuckle Smash Ally 78 Opportunistic Strike Tempus Knuckle Smash Third Wind Sneer Whorl Blade Faction Ak Anon Strike Force V Bertoxxulous Chosen Brownie Rebels Camp Valor Crusaders of Veeshan Fang Breakers Ladies of the Light
https://w.atwiki.jp/kimikage/pages/55.html
チェックボックス列に設定する。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class frmMain Form { /// summary /// コンストラクタ /// /summary public frmMain() { // コンポーネントの初期化 InitializeComponent(); Init(); } /// summary /// 初期化処理 /// /summary private void Init() { DataGridView grdMain = new DataGridView(); // グリッドを追加 this.Controls.Add(grdMain); InitGrd(grdMain); } /// summary /// グリッドの初期化処理 /// /summary /// param name="grd" /param private void InitGrd(DataGridView grd) { // グリッドの位置と大きさを設定 grd.SetBounds(0, 0, this.Width, this.Height); // 行の追加不可 grd.AllowUserToAddRows = false; // 行ヘッダ非表示 grd.RowHeadersVisible = false; // チェックボックス列を追加 grd.Columns.Add(new DataGridViewCheckBoxColumn()); grd.Rows.Add(); } } } チェックボックス列がクリックされたらメッセージを出力 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class frmMain Form { /// summary /// コンストラクタ /// /summary public frmMain() { // コンポーネントの初期化 InitializeComponent(); Init(); } /// summary /// 初期化処理 /// /summary private void Init() { DataGridView dgvMain = new DataGridView(); // グリッドを追加 this.Controls.Add(dgvMain); InitGrd(dgvMain); } /// summary /// グリッドの初期化処理 /// /summary /// param name="dgv" /param private void InitGrd(DataGridView dgv) { // グリッドの位置と大きさを設定 dgv.SetBounds(0, 0, this.Width, this.Height); // 行の追加不可 dgv.AllowUserToAddRows = false; // 行ヘッダ非表示 dgv.RowHeadersVisible = false; // チェックボックス列を追加 DataGridViewCheckBoxColumn col = new DataGridViewCheckBoxColumn(); dgv.Columns.Add(col); dgv.Rows.Add(); dgv.Rows.Add(); dgv.CellContentClick += dgvMain_CellContentClick; } private void dgvMain_CellContentClick(object sender, DataGridViewCellEventArgs e) { DataGridView dgv = (DataGridView)sender; //DataGridViewCheckBoxColumnならば、チェックボックス列がクリックされた if (dgv.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn) { MessageBox.Show(string.Format("{0}行のチェックボックスがクリックされました。", e.RowIndex.ToString())); } } } } コンボボックス列を追加する using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class frmMain Form { /// summary /// コンストラクタ /// /summary public frmMain() { // コンポーネントの初期化 InitializeComponent(); Init(); } /// summary /// 初期化処理 /// /summary private void Init() { DataGridView grdMain = new DataGridView(); // グリッドを追加 this.Controls.Add(grdMain); InitGrd(grdMain); } /// summary /// グリッドの初期化処理 /// /summary /// param name="grd" /param private void InitGrd(DataGridView grd) { // グリッドの位置と大きさを設定 grd.SetBounds(0, 0, this.Width, this.Height); // 行の追加不可 grd.AllowUserToAddRows = false; // 行ヘッダ非表示 grd.RowHeadersVisible = false; // コンボボックス列を追加 grd.Columns.Add(new DataGridViewComboBoxColumn()); // コンボボックスの初期化 InitCmb((DataGridViewComboBoxColumn)grd.Columns[0]); grd.Rows.Add(); // コンボの初期値 grd.Rows[0].Cells[0].Value = "02"; } /// summary /// コンボボックスのリスト項目を設定 /// /summary /// param name="col" /param private void InitCmb(DataGridViewComboBoxColumn col) { DataTable dt = new DataTable(); DataRow row; string strValMember = "val"; string strDisMember = "dis"; dt.Columns.Add(strValMember); dt.Columns.Add(strDisMember); row = dt.NewRow(); row[strValMember] = "01"; row[strDisMember] = "項目①"; dt.Rows.Add(row); row = dt.NewRow(); row[strValMember] = "02"; row[strDisMember] = "項目②"; dt.Rows.Add(row); col.DataSource = dt; col.ValueMember = strValMember; col.DisplayMember = strDisMember; } } } コンボボックス列の値を変更した場合に、メッセージを出力する。 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class frmMain Form { private DataGridView dgvMain = new DataGridView(); private DataGridViewComboBoxEditingControl dgvCmb; /// summary /// コンストラクタ /// /summary public frmMain() { // コンポーネントの初期化 InitializeComponent(); Init(); } /// summary /// 初期化処理 /// /summary private void Init() { // グリッドを追加 this.Controls.Add(dgvMain); this.Initdgv(); } /// summary /// グリッドの初期化処理 /// /summary private void Initdgv() { DataGridViewComboBoxColumn colCmb = new DataGridViewComboBoxColumn(); // グリッドの位置と大きさを設定 this.dgvMain.SetBounds(0, 0, this.Width, this.Height); // 行の追加不可 this.dgvMain.AllowUserToAddRows = false; // 行ヘッダ非表示 this.dgvMain.RowHeadersVisible = false; // コンボボックスの初期化 this.InitColCmb(colCmb); // コンボボックス列を追加 this.dgvMain.Columns.Add(colCmb); // 行追加 this.dgvMain.Rows.Add(); this.dgvMain.Rows.Add(); // イベントハンドラの追加 this.dgvMain.EditingControlShowing += dgvMain_EditingControlShowing; this.dgvMain.CellEndEdit += dgvMain_CellEndEdit; } /// summary /// セルを編集するためのコントロールが表示されたときの処理 /// /summary /// param name="sender" /param /// param name="e" /param private void dgvMain_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { // DataGridViewのコンボボックス編集コントロールが表示されたか if (e.Control is DataGridViewComboBoxEditingControl) { // イベントハンドラの開放用にDataGridViewComboBoxEditingControlを保持 this.dgvCmb = (DataGridViewComboBoxEditingControl)e.Control; // SelectedIndexChangedイベントハンドラを追加 this.dgvCmb.SelectedIndexChanged += dgvCmb_SelectedIndexChanged; } } /// summary /// セルの編集完了 /// /summary /// param name="sender" /param /// param name="e" /param private void dgvMain_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (sender is DataGridView) { // SelectedIndexChangedイベントハンドラを開放 this.dgvCmb.SelectedIndexChanged -= dgvCmb_SelectedIndexChanged; } } /// summary /// コンボの選択値変更時の処理 /// /summary /// param name="sender" /param /// param name="e" /param private void dgvCmb_SelectedIndexChanged(object sender, EventArgs e) { if (sender is DataGridViewComboBoxEditingControl) { DataGridViewComboBoxEditingControl cmb = (DataGridViewComboBoxEditingControl)sender; MessageBox.Show(string.Format("{0} が選択されました。", cmb.Text)); } } /// summary /// コンボボックスのリスト項目を設定 /// /summary /// param name="col" /param private void InitColCmb(DataGridViewComboBoxColumn col) { DataTable dt = new DataTable(); DataRow row; string strValMember = "val"; string strDisMember = "dis"; dt.Columns.Add(strValMember); dt.Columns.Add(strDisMember); row = dt.NewRow(); row[strValMember] = "01"; row[strDisMember] = "項目①"; dt.Rows.Add(row); row = dt.NewRow(); row[strValMember] = "02"; row[strDisMember] = "項目②"; dt.Rows.Add(row); col.DataSource = dt; col.ValueMember = strValMember; col.DisplayMember = strDisMember; } } }
https://w.atwiki.jp/kimikage/pages/75.html
行のドラッグ&ドロップが可能なDataGridView。 ちょっとバグがあるけれど一応動作する。 DataSourceには対応できない。 ViewのCellに直接データを突っ込んで使用可能。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.Drawing; namespace MyReName.ctrl { class DragAbleDataGridView DataGridView { private int mintCurrentRowIndex = -1; private int mintNextRowIndex = -1; private bool mboolMoveToEndRowFlg = false; private int[] dragRowIndex; private bool Flg = true; private Label lblBar = new Label(); public Color DropDawnBarColor { get { return lblBar.BackColor; } set { lblBar.BackColor = value; } } /// summary /// コンストラクタ /// /summary public DragAbleDataGridView() { this.InitCtrl(); } /// summary /// コンポーネントの初期化処理 /// /summary private void InitCtrl() { // DataGridViewの初期設定 this.AutoGenerateColumns = false; this.BackgroundColor = Color.White; this.CellBorderStyle = DataGridViewCellBorderStyle.None; this.RowHeadersVisible = false; this.AllowUserToResizeRows = false; this.SelectionMode = DataGridViewSelectionMode.FullRowSelect; this.AllowUserToAddRows = false; this.AllowUserToDeleteRows = false; this.AllowDrop = true; this.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.ColumnHeadersDefaultCellStyle.WrapMode = DataGridViewTriState.False; // イベントを追加 this.DragDrop += new DragEventHandler(DragAbleDataGridView_DragDrop); this.DragEnter += new DragEventHandler(DragAbleDataGridView_DragEnter); this.MouseDown += new MouseEventHandler(DragAbleDataGridView_MouseDown); this.MouseMove += new MouseEventHandler(DragAbleDataGridView_MouseMove); this.DragOver += new DragEventHandler(DragAbleDataGridView_DragOver); this.DragLeave += new EventHandler(DragAbleDataGridView_DragLeave); this.QueryContinueDrag += new QueryContinueDragEventHandler(DragAbleDataGridView_QueryContinueDrag); this.RowValidating += new DataGridViewCellCancelEventHandler(DragAbleDataGridView_RowValidating); // ドラッグ中に表示するバーを追加 this.Controls.Add(lblBar); lblBar.Visible = false; lblBar.BackColor = Color.Red; lblBar.Size = new Size(this.Width, 2); } /// summary /// MouseDownイベント /// /summary /// param name="sender" /param /// param name="e" /param private void DragAbleDataGridView_MouseDown(object sender, MouseEventArgs e) { mintCurrentRowIndex = -1; // 左クリック以外はリターン if ((e.Button MouseButtons.Left) != MouseButtons.Left) { return; } // セルクリック以外はリターン DataGridView.HitTestInfo hitInfo = this.HitTest(e.X, e.Y); if (hitInfo.Type != DataGridViewHitTestType.Cell) { return; } mintCurrentRowIndex = hitInfo.RowIndex; // 既に選択されているセルを選択している場合(ここの動作がうまくいかない…) if (this.Rows[mintCurrentRowIndex].Selected ModifierKeys == Keys.None) { ReSetDragRowsIndexies(); Flg = true; } // 未選択のセルを選択している場合 else { dragRowIndex = null; Flg = false; } } /// summary /// 行の検証時の処理 /// /summary /// param name="sender" /param /// param name="e" /param private void DragAbleDataGridView_RowValidating(object sender, DataGridViewCellCancelEventArgs e) { if (Flg) { e.Cancel = true; Flg = false; } } /// summary /// MouseMoveイベント /// /summary /// param name="sender" /param /// param name="e" /param private void DragAbleDataGridView_MouseMove(object sender, MouseEventArgs e) { // 左ボタン以外はリターン if ((e.Button MouseButtons.Left) != MouseButtons.Left) { return; } // Row未選択はリターン if (mintCurrentRowIndex == -1) { return; } // ドラッグ開始 this.DoDragDrop(mintCurrentRowIndex, DragDropEffects.Move); } /// summary /// ドラッグ対象行のインデックスを記憶 /// /summary private void ReSetDragRowsIndexies() { dragRowIndex = new int[this.SelectedRows.Count]; for (int i = 0; i this.SelectedRows.Count; i++) { dragRowIndex[i] = this.SelectedRows[i].Index; } } /// summary /// DragOverイベント /// /summary /// param name="sender" /param /// param name="e" /param private void DragAbleDataGridView_DragOver(object sender, DragEventArgs e) { if (mintCurrentRowIndex == -1) { return; } e.Effect = DragDropEffects.Move; if (dragRowIndex == null) { ReSetDragRowsIndexies(); } // ドラッグ位置を取得 Point clientPoint = this.PointToClient(new Point(e.X, e.Y)); DataGridView.HitTestInfo hitInfo = this.HitTest(clientPoint.X, clientPoint.Y); mboolMoveToEndRowFlg = false; if (hitInfo.RowIndex == -1) { if (mintCurrentRowIndex == this.Rows.Count - 1) { mboolMoveToEndRowFlg = true; } } else { mintNextRowIndex = hitInfo.RowIndex; } if (mboolMoveToEndRowFlg) { Rectangle rec = this.GetRowDisplayRectangle(mintNextRowIndex, true); lblBar.Location = new Point(0, rec.Bottom); lblBar.Visible = true; } else if (mintCurrentRowIndex == mintNextRowIndex mintCurrentRowIndex == this.Rows.Count - 1) { Rectangle rec = this.GetRowDisplayRectangle(mintNextRowIndex, true); lblBar.Location = new Point(0, rec.Top); lblBar.Visible = true; } else if (mintCurrentRowIndex != mintNextRowIndex) { Rectangle rec = this.GetRowDisplayRectangle(mintNextRowIndex, true); lblBar.Location = new Point(0, rec.Top); mintCurrentRowIndex = mintNextRowIndex; lblBar.Visible = true; } } /// summary /// DataGridViewの外へドラッグしたらドラッグをキャンセル /// /summary /// param name="sender" /param /// param name="e" /param private void DragAbleDataGridView_DragLeave(object sender, EventArgs e) { if (!lblBar.Visible) { return; } ExitDrag(); } /// summary /// DragEnter /// /summary /// param name="sender" /param /// param name="e" /param private void DragAbleDataGridView_DragEnter(object sender, DragEventArgs e) { if (lblBar.Visible) { return; } e.Effect = DragDropEffects.All; } /// summary /// ドラッグ継続中 /// /summary /// param name="sender" /param /// param name="e" /param private void DragAbleDataGridView_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) { // 右クリック押下時 if ((e.KeyState 2) == 2) { // ドラッグをキャンセル e.Action = DragAction.Cancel; ExitDrag(); } } /// summary /// 行データの移動 /// /summary /// param name="FromIndex" /param /// param name="ToIndex" /param /// returns 実際の移動先インデックス /returns private int MoveTo(int FromIndex, int ToIndex) { DataGridViewRow row; int MoveToIndex = ToIndex; if (FromIndex != ToIndex) { row = (DataGridViewRow)this.Rows[FromIndex].Clone(); for (int i = 0; i this.Columns.Count; i++) { row.Cells[i].Value = this.Rows[FromIndex].Cells[i].Value; } if (FromIndex ToIndex) { this.Rows.RemoveAt(FromIndex); this.Rows.Insert(ToIndex, row); } else if (FromIndex ToIndex) { if (mboolMoveToEndRowFlg) { this.Rows.RemoveAt(FromIndex); this.Rows.Insert(ToIndex, row); } else { this.Rows.RemoveAt(FromIndex); this.Rows.Insert(ToIndex - 1, row); MoveToIndex = ToIndex - 1; } } } return MoveToIndex; } private void DragAbleDataGridView_DragDrop(object sender, DragEventArgs e) { // 行のDragDropの場合 if (lblBar.Visible) { Flg = false; Array.Sort(dragRowIndex); int ShiftFront = 0; int ShiftBack = 0; int MoveFromIndex = 0; int MoveToIndex = 0; int MinRowIndex = mintCurrentRowIndex; int MaxRowIndex = mintCurrentRowIndex; int SelectionStaIndex = 0; // 行を移動 for (int i = 0; i dragRowIndex.GetLength(0); i++) { MoveFromIndex = dragRowIndex[i]; MoveToIndex = mintCurrentRowIndex; if (MinRowIndex MoveFromIndex) { MinRowIndex = MoveFromIndex; } else if (MinRowIndex MoveToIndex) { MinRowIndex = MoveToIndex; } if (MaxRowIndex MoveFromIndex) { MaxRowIndex = MoveFromIndex; } else if (MaxRowIndex MoveToIndex) { MaxRowIndex = MoveToIndex; } if (i 0) { if (MoveFromIndex MoveToIndex) { ShiftFront--; MoveFromIndex += ShiftFront; } else if (MoveFromIndex MoveToIndex) { if (dragRowIndex[i - 1] = MoveToIndex) { ShiftBack++; MoveToIndex += ShiftBack; } } } if (i == 0) { SelectionStaIndex = MoveTo(MoveFromIndex, MoveToIndex); } else { MoveTo(MoveFromIndex, MoveToIndex); } } // 移動後の行を選択 this.CurrentCell = this.Rows[SelectionStaIndex + ShiftFront].Cells[0]; this.ClearSelection(); for (int i = 0; i dragRowIndex.GetLength(0); i++) { this.Rows[SelectionStaIndex + ShiftFront + i].Selected = true; } ExitDrag(); } // DataGridView外からのDragDropの場合 else { //DragDropされたファイルパスをセルに追加 if (e.Data.GetDataPresent(DataFormats.FileDrop)) { foreach (string filePath in (string[])e.Data.GetData(DataFormats.FileDrop)) { if (this.Columns.Count 0) { this.Rows.Add(); this.Rows[this.Rows.Count - 1].Cells[0].Value = filePath; } } } } } /// summary /// ドラッグの終了処理 /// /summary private void ExitDrag() { mintCurrentRowIndex = -1; //_DragMode = eDraggingMode.None; lblBar.Visible = false; this.DoDragDrop(mintCurrentRowIndex, DragDropEffects.None); } } }
https://w.atwiki.jp/mysqlmemo/pages/24.html
原則 ユーザーによる列の追加、削除を許可するDataGridViewの機能はOffとし、列の追加、列の削除ボタンを作って対応する(列追加許可をOnにすると動作がよくわからない。またOffにするとRowHeaderを表示する必要がなくなり、すっきりする?) DataTableにバインドされているとき バインド元のDataTableでRows.Addを行うときに、もしCurrentCellが新規行のとき、動作が何か変。新規行上で動作がへんになるので、いっそユーザーによる追加を許可しない様にすればいいのか。 DataTableにバインドするときは、なぜかDataGridViewRow.DataBoundItemが(一見DataRowになりそうだが)DataRowViewになる これは、DataTableがIListSourceを実装しており、GetListメソッドで返す値がDataRowViewだからかもしれない (制約を外して)エラーメッセージを出す方法 以下がサンプルコード。 これでてっとり早く、制約を外して、かつエラーメッセージを出すことができる。(もしかしたら動作が遅いかもしれない) サーバーに書きこむ前には、DataSet.EnForceConstraints = Trueとする(ここで、制約違反が残っている場合、例外が発生してConstraintが有効にならない)。 Private Sub DataGridView1_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValidated Dim currentSourceRowView As DataRowView = CType(DataGridView1.Rows(e.RowIndex).DataBoundItem, DataRowView) If Not currentSourceRowView Is Nothing Then currentSourceRowView.EndEdit() End If Try Me.ClearErrors() DataSet1.EnforceConstraints = True Catch ex As ConstraintException 制約違反については、無視する End Try DataSet1.EnforceConstraints = False 現在の行以外でのエラーアイコンを描写させるために必要 DataGridView1.Refresh() End Sub Private Sub ClearErrors() Dim errorRows = DataSet1.DataTable1.GetErrors() For Each row In errorRows row.RowError = Nothing Dim errorCells = row.GetColumnsInError() For Each cell In errorCells row.SetColumnError(cell.ColumnName, Nothing) Next Next End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load DataSet1.EnforceConstraints = False End Sub
https://w.atwiki.jp/memo77/pages/46.html
PageLastUpdate 2007-11-13/today - /yesterday - DataGridViewSynchronizer 2007/11/13 上下に並べたふたつのDataGridViewの列表示を同期させるクラス。 Option Strict On Public Class DataGridViewSynchronizer Private grd1 As DataGridView Private grd2 As DataGridView Public Sub Add(ByRef datagridview1 As DataGridView, ByRef datagridview2 As DataGridView) Try Me.grd1 = datagridview1 Me.grd2 = datagridview2 For Each column As DataGridViewColumn In grd1.Columns If grd2.Columns.Contains(column.Name) = False Then MessageBox.Show("連動させるグリッドの列構成が違います。完全に一致したグリッドでなければ連動させることはできません。") End If Next For Each column As DataGridViewColumn In grd2.Columns If grd1.Columns.Contains(column.Name) = False Then MessageBox.Show("連動させるグリッドの列構成が違います。完全に一致したグリッドでなければ連動させることはできません。") End If Next grd1.SuspendLayout() grd2.SuspendLayout() For Each column1 As DataGridViewColumn In grd1.Columns Dim column2 As DataGridViewColumn = grd2.Columns(column1.Name) column2.DisplayIndex = column1.DisplayIndex column2.Frozen = column1.Frozen column2.HeaderText = column1.HeaderText column2.Resizable = column1.Resizable column2.Visible = column1.Visible column2.Width = column1.Width column2.AutoSizeMode = DataGridViewAutoSizeColumnMode.None Next AddHandler grd1.ColumnWidthChanged, AddressOf ColumnWidthChanged1 AddHandler grd1.ColumnDisplayIndexChanged, AddressOf ColumnDisplayIndexChanged1 AddHandler grd1.Scroll, AddressOf Scroll1 AddHandler grd1.ColumnStateChanged, AddressOf ColumnStateChanged1 AddHandler grd2.ColumnWidthChanged, AddressOf ColumnWidthChanged2 AddHandler grd2.ColumnDisplayIndexChanged, AddressOf ColumnDisplayIndexChanged2 AddHandler grd2.Scroll, AddressOf Scroll2 AddHandler grd2.ColumnStateChanged, AddressOf ColumnStateChanged2 grd1.ResumeLayout() grd2.ResumeLayout() Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub ColumnWidthChanged1(ByVal sender As Object, ByVal e As DataGridViewColumnEventArgs) Try If grd2.Columns(e.Column.Name).Width e.Column.Width Then grd2.Columns(e.Column.Name).Width = e.Column.Width End If Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub ColumnDisplayIndexChanged1(ByVal sender As Object, ByVal e As DataGridViewColumnEventArgs) Try If grd2.Columns(e.Column.Name).DisplayIndex e.Column.DisplayIndex Then grd2.Columns(e.Column.Name).DisplayIndex = e.Column.DisplayIndex End If Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub Scroll1(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Try If grd2.HorizontalScrollingOffset grd1.HorizontalScrollingOffset Then grd2.HorizontalScrollingOffset = grd1.HorizontalScrollingOffset End If Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub ColumnStateChanged1(ByVal sender As Object, ByVal e As DataGridViewColumnStateChangedEventArgs) Try Select Case e.StateChanged Case DataGridViewElementStates.Frozen If grd2.Columns(e.Column.Name).Frozen e.Column.Frozen Then grd2.Columns(e.Column.Name).Frozen = e.Column.Frozen End If Case DataGridViewElementStates.Resizable If grd2.Columns(e.Column.Name).Resizable e.Column.Resizable Then grd2.Columns(e.Column.Name).Resizable = e.Column.Resizable End If Case DataGridViewElementStates.Selected If grd2.Columns(e.Column.Name).Selected e.Column.Selected Then grd2.Columns(e.Column.Name).Selected = e.Column.Selected End If Case DataGridViewElementStates.Visible If grd2.Columns(e.Column.Name).Visible e.Column.Visible Then grd2.Columns(e.Column.Name).Visible = e.Column.Visible End If End Select Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub ColumnWidthChanged2(ByVal sender As Object, ByVal e As DataGridViewColumnEventArgs) Try If grd1.Columns(e.Column.Name).Width e.Column.Width Then grd1.Columns(e.Column.Name).Width = e.Column.Width End If Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub ColumnDisplayIndexChanged2(ByVal sender As Object, ByVal e As DataGridViewColumnEventArgs) Try If grd1.Columns(e.Column.Name).DisplayIndex e.Column.DisplayIndex Then grd1.Columns(e.Column.Name).DisplayIndex = e.Column.DisplayIndex End If Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub Scroll2(ByVal sender As Object, ByVal e As System.Windows.Forms.ScrollEventArgs) Try If grd1.HorizontalScrollingOffset grd2.HorizontalScrollingOffset Then grd1.HorizontalScrollingOffset = grd2.HorizontalScrollingOffset End If Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub ColumnStateChanged2(ByVal sender As Object, ByVal e As DataGridViewColumnStateChangedEventArgs) Try Select Case e.StateChanged Case DataGridViewElementStates.Frozen If grd1.Columns(e.Column.Name).Frozen e.Column.Frozen Then grd1.Columns(e.Column.Name).Frozen = e.Column.Frozen End If Case DataGridViewElementStates.Resizable If grd1.Columns(e.Column.Name).Resizable e.Column.Resizable Then grd1.Columns(e.Column.Name).Resizable = e.Column.Resizable End If Case DataGridViewElementStates.Selected If grd1.Columns(e.Column.Name).Selected e.Column.Selected Then grd1.Columns(e.Column.Name).Selected = e.Column.Selected End If Case DataGridViewElementStates.Visible If grd1.Columns(e.Column.Name).Visible e.Column.Visible Then grd1.Columns(e.Column.Name).Visible = e.Column.Visible End If End Select Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub Remove() Try RemoveHandler grd1.ColumnWidthChanged, AddressOf ColumnWidthChanged1 RemoveHandler grd1.ColumnDisplayIndexChanged, AddressOf ColumnDisplayIndexChanged1 RemoveHandler grd1.Scroll, AddressOf Scroll1 RemoveHandler grd1.ColumnStateChanged, AddressOf ColumnStateChanged1 RemoveHandler grd2.ColumnWidthChanged, AddressOf ColumnWidthChanged2 RemoveHandler grd2.ColumnDisplayIndexChanged, AddressOf ColumnDisplayIndexChanged2 RemoveHandler grd2.Scroll, AddressOf Scroll2 RemoveHandler grd2.ColumnStateChanged, AddressOf ColumnStateChanged2 Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub End Class comment このページの記述で聞きたいこととか間違ってることとかありましたらコメントを。 名前 コメント すべてのコメントを見る
https://w.atwiki.jp/atachi/pages/39.html
データグリッドの機能 [#mf0696a7] データグリッドの設定 [#md3a96c1] カラム [#h1c86b3c] カラムの設定 [#h666d223] カラムの種類 [#kce03342] ボタンをカラムに表示する [#ufea0d87] コンボボックスをカラムに表示する 参考サイト データグリッドの機能 カラム自動生成機能 DataGrid.ItemsSourceに設定されたデータの型情報を元に、データグリッドのカラムを自動生成する機能を持ちます。 カラムの定義を記述する必要がなく、データを与えるだけですべての情報が表示されることができます。 逆に表示するデータの項目を制限したい場合やカラムの順番の変更、表示形式の変更などを行いたい場合はこの機能を無効にし、カラムの定義を記述していく必要があります。 カラム自動生成機能の制御はDataGrid.AutoGenerateColumns プロパティのフラグで設定できます。 データグリッドの設定 名前 プロパティ名 設定例 備考 読み込み専用モード DataGrid.IsReadOnly True グリッド全体を読み取り専用モードにする。編集モードにならない ソートの有効 DataGrid.AllowSorting True レコードのソートを許可する ユーザーによるレコードの追加 DataGrid.CanUserAddRows True 実行時にユーザーによってレコードの追加を許可する ユーザーによるレコードの削除 DataGrid.CanUserDeleteRows True 実行時にユーザーによってレコードの削除を許可する ユーザーによるカラム位置の変更 DataGrid.CanUserReorderColumns True 実行時にユーザーによってカラムの場所の移動を許可する ユーザーによるカラム幅の変更 DataGrid.CanUserResizeColumns True 実行時にユーザーによってカラムの幅の変更を許可する カラムの自動生成機能 DataGrid.AutoGeneratingColumn True データソースから自動的にカラムの生成を行う カラム カラムの設定 名前 プロパティ名 設定例 備考 ヘッダー名 DataGridColumn.Header 文字列 ヘッダー名に設定したい文字列 ヘッダーの幅 DataGridColumn.Width 数字 ヘッダーの幅 * すべてのカラムの幅の合計がグリッドの幅より小さい場合に、グリッド幅まで広げる SizeToCells 列の中でセルの幅が最大のものに合わせる SizeToHeader セルの幅をヘッダー名の幅に合わせる 読み取り専用列 DataGridColumn.IsReadOnly True カラムを読み取り専用にするグリッド全体を読み取り専用にするにはデータグリッドの設定を参照。 カラムの種類 定義済みのカラムを使用する。または、独自のカラムを定義することも可能。 カラム名 説明 DataGridTextColumn TextBlockまたはTextBoxによるカラムの描画を行う。文字列の表示や編集を必要とする場合に使用するカラム DataGridCheckBoxColumn データがBoolean型でCheckBoxによるカラムの描画を行う。 DataGridComboBoxColumn ComboBoxによるカラムの描画を行う。 DataGridHyperlinkColumn データをURIとして扱う。Hyperlinkによるカラムの描画を行う。 DataGridTemplateColumn データテンプレートを使用して独自のコントロールを使用してカラムの描画を行う。 ボタンをカラムに表示する DataGridTemplateColumnを使ってカラムを定義することで、カラムに任意のレイアウトで表示することができる。 下記の例はカラムにボタンを表示するサンプルです。 DataGrid DataGrid.Columns DataGridTemplateColumn DataGridTemplateColumn.CellTemplate DataTemplate Button Content="テスト" / /DataTemplate /DataGridTemplateColumn.CellTemplate /DataGridTemplateColumn /DataGrid.Columns /DataGrid コンボボックスをカラムに表示する DataGridのカラム設定でDataGridComboBoxColumnを使用します。 表示されるコンボボックスの選択項目をDataGridのアイテム以外から設定する場合には、少し工夫が必要となります。 なぜかDataGridComboBoxColumn.ItemsSourceに直接バインドすることができないので、EditingElementStyleプロパティとElementStyleプロパティを使って直接コンボボックスのItemsSourceに表示させたい項目のコレクションをバインドします。 Window Grid DataGrid AutoGenerateColumns="False" Height="232" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="479" ItemsSource="{Binding Studios}" DataGrid.Columns DataGridTextColumn Header="映画名" Binding="{Binding Label}" Width="150"/ DataGridComboBoxColumn Header="DataGridComboBoxのテスト" SelectedItemBinding="{Binding CategoryType}" DataGridComboBoxColumn.ElementStyle Style TargetType="{x Type ComboBox}" Setter Property="DisplayMemberPath" Value="ViewName" / Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x Type Window} },Path=DataContext.Types}" / /Style /DataGridComboBoxColumn.ElementStyle DataGridComboBoxColumn.EditingElementStyle Style TargetType="{x Type ComboBox}" Setter Property="DisplayMemberPath" Value="ViewName" / Setter Property="ItemsSource" Value="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x Type Window} },Path=DataContext.Types}" / /Style /DataGridComboBoxColumn.EditingElementStyle /DataGridComboBoxColumn !-- ↓の方法ではコンボボックスの一覧にItemsSourceを使うことができない -- DataGridComboBoxColumn Header="DataGridComboBoxのテスト" SelectedItemBinding="{Binding CategoryType}" ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x Type Window} },Path=DataContext.Types}" DisplayMemberPath="ViewName"/ /DataGrid.Columns /DataGrid /Grid /Window MyDataはXAMLの分離コードでWindowのDataContextに設定します。 public class MyData { public MyData() { _Types.Add(new CategoryType { ViewName = "Type A" }); _Types.Add(new CategoryType { ViewName = "Type B" }); _Types.Add(new CategoryType { ViewName = "Type C" }); _Studios.Add(new Studio { Label = "A", CategoryType = _Types.ElementAt(0) }); _Studios.Add(new Studio { Label = "B", CategoryType = _Types.ElementAt(2) }); } public ICollection Studio Studios { get { return _Studios; } } public ICollection CategoryType Types { get { return _Types; } } private ICollection Studio _Studios = new ObservableCollection Studio (); private ICollection CategoryType _Types = new List CategoryType (); } public class Studio { public string Label { get; set; } public CategoryType CategoryType { get; set; } } public class CategoryType { public string ViewName { get; set; } } 参考サイト MSDN DataGrid DataGridの使い方 DataGridで行ごとに色を変えるには? セル内のボタンを表示・非表示する方法 動的にカラムの表示非表示を切り替えるDataGridの作成
https://w.atwiki.jp/eqtunarejp/pages/121.html
Item Pre Progression Type Task NPC Start Timeshear Purple Octagonal Fragment Oceangreen Azia ◯ Group A Corrupted Arch Priest Apothecary Cadmael Oceangreen Village Beza Remove the Head and the Disease Will Die Caze Mini Raid The Bubonian are Coming! Jerom Bertrand Dena ◯ Group Freedom! Raxtor Darkpawm Oceangreen Hills Ena 1/6 Beat the Blackburrow Boss Fena × Disrupting the Ritual Elder Mystic Foppye Geza ◯ 2/6 Solo Familiarity is Key Captain Hiran Tillin Heda Group Stop the Contamination Timeshear Orange Moon Fragment Kithicor Azia × 2/4 Group Safe Passage Commander Barvian Bloody Kithicor Beza ◯ Bitter Victuals Firiona Vie Timeshear Red Hexagonal Fragment Field of Scale Azia ◯ 5/5 Group The Price of Knowledge Jaled`Dar Field of Scale Beza The Brood of an Emperor Caze An Impenetrable Shield Dena Audience with the Warmaster Ena Defeat the Dragonbane Phalanx Timeshear Green Hexagonal Fragment Rathe Azia ◯ Group Cruel Overseers Trilyaris Toskirakk Beza Spies, Lies, and Prison Cells Caze Hiding in Plain Sight Dena ◯ The Crystal Bloom Ulgin Darkhammer Korascian Warrens Ena ◯ 1/6 Murdunk s Last Stand Ylatra the Vassal Timeshear Blue Moon Fragment Kuua Azia × 2/11 Group Studying the Portal Yemall the Arcane City of Dranik Beza Holding the Fort General Vurig the Imposing Old Bloodfields Timeshear Black Square Fragment Discord Azia ◯ 4/11 Group Kill the Shearspawn Telivar S`Vik Korafax, Home of the Riders Beza Inside Information Caze Meeting Adjourned Dena Mini raid Stardouser