約 5,522,943 件
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/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/58.html
コンボリストに画像を表示する using System; using System.Drawing; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class frmMain Form { /// summary /// コンストラクタ /// /summary public frmMain() { // コンポーネントの初期化 InitializeComponent(); Init(); } /// summary /// 初期化処理 /// /summary private void Init() { Bitmap img; ExComboBox cmb = new ExComboBox(); ImageList imgList = new ImageList(); img = new Bitmap(15, 15); Graphics.FromImage(img).DrawString("あ", new Font("MS ゴシック", 9F, System.Drawing.FontStyle.Regular), Brushes.Green, 0, 0); imgList.Images.Add(img); img = new Bitmap(15, 15); Graphics.FromImage(img).DrawString("い", new Font("MS ゴシック", 9F, System.Drawing.FontStyle.Regular), Brushes.Blue, 0, 0); imgList.Images.Add(img); cmb.ImageList = imgList; cmb.Items.AddRange(new Object[] { "山", "川", "空" }); this.Controls.Add(cmb); } } public class ExComboBox ComboBox { private ImageList imgList = null; public ImageList ImageList { get { return imgList; } set { imgList = value; } } public ExComboBox() { this.DrawMode = DrawMode.OwnerDrawFixed; } /// summary /// リスト項目の描画 /// /summary /// param name="e" /param protected override void OnDrawItem(DrawItemEventArgs e) { e.DrawBackground(); e.DrawFocusRectangle(); Rectangle bounds = new Rectangle(); bounds = e.Bounds; string str = this.Items[e.Index].ToString(); try { if (imgList != null) { if (imgList.Images.Count e.Index) { // imgListに設定された画像を描画 e.Graphics.DrawImage(imgList.Images[e.Index], bounds.Left, bounds.Top, bounds.Height, bounds.Height); // itemsに設定された文字列を描画 e.Graphics.DrawString(str, e.Font, new SolidBrush(e.ForeColor), bounds.Left + bounds.Height, bounds.Top); } else { // itemsに設定された文字列を描画 e.Graphics.DrawString(str, e.Font, new SolidBrush(e.ForeColor), bounds.Left + bounds.Height, bounds.Top); } } else { // itemsに設定された文字列を描画 e.Graphics.DrawString(str, e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top); } } catch { // itemsに設定された文字列を描画 e.Graphics.DrawString(str, e.Font, new SolidBrush(e.ForeColor), bounds.Left, bounds.Top); } } } }
https://w.atwiki.jp/lafe/pages/20.html
フラットコンボボックスを余所でも使うかもしれないので // CComboBoxProxy.h /////////////////////////////////////////////////////////////////////////////////////////// // CComboBoxProxy class CComboBoxProxy public CWindowImpl CComboBoxProxy, CComboBox , public CTrackMouseLeave CComboBoxProxy { private enum { s_kcxyBorder = 2 }; enum _ComboState { _comboNormal, _comboHot, _comboPressed }; // Data members _ComboStatem_state; intm_nDrawStyle; BOOLm_bExistManifest; public // コンストラクタ CComboBoxProxy(); boolFlatComboBox_Install(HWND hWndCombo); voidFlatComboBox_UnInstall(); voidSetDrawStyle(int nStyle); public // メッセージマップ BEGIN_MSG_MAP(CComboBoxProxy) MSG_WM_PAINT( OnPaint ) CHAIN_MSG_MAP(CTrackMouseLeave CComboBoxProxy ) END_MSG_MAP() private voidOnPaint(CDCHandle dc); private void_DoComboPaint(CDCHandle dc); void_DrawFlatThumb(CDCHandle dc); void_DrawFlatCombo(CDCHandle dc, _ComboState state); CRect_GetOriginalThumbRect(); CRect_GetFlatThumbInvalidateRect(); CRect_GetFlatComboInvalidateRect(); void_SetUseXPTheme(HWND hWnd, BOOL bUse); }; // ComboBoxProxy.cpp #include "ComboBoxProxy.h" //////////////////////////////////////////////////////////////////////////////////////// // CComboBoxProxy // コンストラクタ CComboBoxProxy CComboBoxProxy() m_state(_comboNormal) , m_nDrawStyle(SKN_COMBO_STYLE_DEFAULT) , m_bExistManifest(TRUE) { } bool CComboBoxProxy FlatComboBox_Install(HWND hWndCombo) { ATLVERIFY( SubclassWindow(hWndCombo) ); return true; } void CComboBoxProxy FlatComboBox_UnInstall() { if ( IsWindow() ) { UnsubclassWindow(); } } void CComboBoxProxy SetDrawStyle(int nStyle) { m_nDrawStyle = nStyle; if (nStyle == SKN_COMBO_STYLE_THEME m_bExistManifest) { _SetUseXPTheme(m_hWnd, TRUE); } else { _SetUseXPTheme(m_hWnd, FALSE); } } ///////////////////////////////////////////////////////////////////////////////////// // メッセージマップ void CComboBoxProxy OnPaint(CDCHandle dc) { if ( m_nDrawStyle == SKN_COMBO_STYLE_DEFAULT || (m_nDrawStyle == SKN_COMBO_STYLE_THEME !m_bExistManifest) ) { // スタイルがデフォルトかテーマなのにmanifestファイルが存在しないとき CRectrc; GetUpdateRect( rc, FALSE); ValidateRect(NULL);// validate the whole // invalidate only the internal rect CRectrcCombo = _GetFlatComboInvalidateRect(); CRectrcThumb = _GetFlatThumbInvalidateRect(); CRectrcUpdate = rc rcCombo; InvalidateRect( rcUpdate, FALSE); rcUpdate = rc rcThumb; InvalidateRect( rcUpdate, FALSE); // Update LRESULTlRet = DefWindowProc(); CClientDCdc(m_hWnd); _DoComboPaint(dc.m_hDC); } else { SetMsgHandled(FALSE); } } // ////////////////////////////////////////////////////////////////////////////////////// // private void CComboBoxProxy _DoComboPaint(CDCHandle dc) { _DrawFlatCombo(dc, m_state); _DrawFlatThumb(dc); } void CComboBoxProxy _DrawFlatThumb(CDCHandle dc) { CRectrc = _GetOriginalThumbRect(); dc.DrawEdge(rc, BDR_RAISEDINNER, BF_RECT); rc.DeflateRect(1, 1); COLORREFclrBtnFace = GetSysColor(COLOR_BTNFACE); dc.Draw3dRect(rc, clrBtnFace, clrBtnFace); } void CComboBoxProxy _DrawFlatCombo(CDCHandle dc, _ComboState state) { COLORREFclrBtnFace = GetSysColor(COLOR_BTNFACE); CRectrc; GetClientRect( rc); dc.Draw3dRect(rc, clrBtnFace, clrBtnFace); rc.DeflateRect(1, 1); switch (state) { case _comboNormal dc.DrawEdge(rc, BDR_SUNKENOUTER, BF_RECT); break; case _comboHot dc.DrawEdge(rc, BDR_RAISEDINNER, BF_RECT); break; case _comboPressed break; } } CRect CComboBoxProxy _GetOriginalThumbRect() { CRectrc; GetClientRect( rc); rc.right-= s_kcxyBorder; rc.left = rc.right - GetSystemMetrics(SM_CXHTHUMB); rc.top+= s_kcxyBorder; rc.bottom-= s_kcxyBorder; return rc; } CRect CComboBoxProxy _GetFlatThumbInvalidateRect() { CRectrc = _GetOriginalThumbRect(); rc.DeflateRect(2, 2); return rc; } CRect CComboBoxProxy _GetFlatComboInvalidateRect() { CRectrc; GetClientRect( rc); rc.DeflateRect(2, 2); rc.right -= GetSystemMetrics(SM_CXHTHUMB); return rc; } void CComboBoxProxy _SetUseXPTheme(HWND hWnd, BOOL bUse) { if (bUse) { SetWindowTheme( hWnd, L" ", L"COMBOBOX" ); } else { SetWindowTheme( hWnd, L" ", L" " ); } }
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/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/osinko/pages/114.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 BindingTest { /// summary /// /// TextBox ←→ BindingSource ←→ DataGridView /// /// <要点> /// ・BindingSourceはAddを利用する事によりリスト構造に出来る /// ・データーグリッドの選択位置によりbindingSource.Currentオブジェクトは選択中の物がセットされる /// ・TextBoxへはDataBindingsの機能により選択中のオブジェクトのプロパティが反映される。テキストボックスで行った変更はBindingSourceへ反映される /// /// /summary public partial class Form1 Form { public BindingSource bindingSource1 = new BindingSource(); public Form1() { InitializeComponent(); PopulateBindingSourceWithFonts(); } private void PopulateBindingSourceWithFonts() { bindingSource1.Add(new Person("test1", 12)); bindingSource1.Add(new Person("test2", 24)); bindingSource1.Add(new Person("test3", 48)); bindingSource1.Add(new Person("test4", 64)); dataGridView1.DataSource = bindingSource1; dataGridView1.AutoGenerateColumns = true; textBox1.DataBindings.Add("Text", bindingSource1, "Name"); } } class Person { public string Name { get; set; } public int ID { get; set; } public Person(string name,int id) { Name = name; ID = id; } } }
https://w.atwiki.jp/kimikage/pages/59.html
似非チェックボックスドロップダウンリスト ドロップダウンリスト部分はToolStripDropDownで代用 それっぽく見える気がする using System; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; namespace WindowsFormsApplication1 { /// summary /// メインフォーム /// /summary public partial class frmMain Form { /// summary /// コンストラクタ /// /summary public frmMain() { // コンポーネントの初期化 InitializeComponent(); Init(); } /// summary /// 初期化処理 /// /summary private void Init() { CheckComboBox cmb = new CheckComboBox(); cmb.Items.AddRange(new object[] { "One", "Two", "Three" }); this.Controls.Add(cmb); } } #region "チェックコンボ" /// summary /// チェックコンボ /// /summary public partial class CheckComboBox ComboBox { private ExToolStripDropDown mExDropDownList; /// summary /// コンストラクタ /// /summary public CheckComboBox() { base.DropDownHeight = 1; base.DropDownStyle = ComboBoxStyle.DropDown; mExDropDownList = new ExToolStripDropDown(this); } /// summary /// KeyPress処理 /// /summary /// param name="e" /param protected override void OnKeyPress(KeyPressEventArgs e) { // キー入力を無効化 e.Handled = true; } /// summary /// KeyDown処理 /// /summary /// param name="e" /param protected override void OnKeyDown(KeyEventArgs e) { // キー入力を無効化 e.Handled = true; } /// summary /// DropDown時 /// /summary /// param name="e" /param protected override void OnDropDown(EventArgs e) { mExDropDownList.SetItems(this.Items); mExDropDownList.Show(this, 0, this.Height); mExDropDownList.Focus(); } #region "チェックコンボ用ドロップダウンリスト" /// summary /// チェックコンボ用のドロップダウンリスト /// /summary private partial class ExToolStripDropDown ToolStripDropDown { private CheckComboBox chCmb; // チェックボックス記憶用 private ArrayList chkArry = new ArrayList(); /// summary /// コンストラクタ /// /summary /// param name="cmb" /param public ExToolStripDropDown(CheckComboBox cmb) { chCmb = cmb; } /// summary /// ドロップダウンリストに項目をセット /// /summary /// param name="cmbItems" /param public void SetItems(ComboBox.ObjectCollection cmbItems) { if (CheckItemsChanged(cmbItems)) { ToolStripControlHost h; CheckBox chk; // クリア処理 this.Items.Clear(); chkArry.Clear(); chCmb.Text = String.Empty; // チェックボックス追加 for (int i = 0; i cmbItems.Count; i++) { // チェックボックスの設定 chk = new CheckBox(); chkArry.Add(chk); chk.Text = cmbItems[i].ToString(); chk.Checked = false; chk.AutoSize = false; chk.BackColor = Color.White; chk.Size = new System.Drawing.Size(chCmb.Width, chk.Height); // チェック状態変更時のイベント追加 chk.CheckedChanged += chk_CheckedChanged; // ToolStripDropDOwnListのItemsにチェックボックスを追加 h = new ToolStripControlHost(chk); h.AutoSize = false; h.Size = chk.Size; this.Items.Add(h); } } } /// summary /// Itemsの内容が変更されたかどうかをチェック /// /summary /// param name="cmbItems" /param /// returns true 変更された,false 変更されていない /returns private Boolean CheckItemsChanged(ComboBox.ObjectCollection cmbItems) { // 項目数の変更チェック if (chkArry.Count != cmbItems.Count) { return true; } // 各項目のテキスト内容の変更チェック for (int i = 0; i chkArry.Count; i++) { if (cmbItems[i].ToString() != ((CheckBox)chkArry[i]).Text) { return true; } } return false; } /// summary /// チェックボックスのチェック状態が変更されたとき /// /summary /// param name="sender" /param /// param name="e" /param private void chk_CheckedChanged(object sender, EventArgs e) { SetText(); } /// summary /// チェックされたテキストをカンマ区切りでコンボに出力 /// /summary private void SetText() { StringBuilder sb = new StringBuilder(); CheckBox chk; for (int i = 0; i chkArry.Count; i++) { chk = (CheckBox)chkArry[i]; // チェックされてるか if (chk.Checked) { sb.AppendFormat("{0},", chk.Text); } } chCmb.Text = sb.ToString(); if (chCmb.Text.Length 0) { // 末尾のカンマ除去 chCmb.Text = chCmb.Text.Remove(chCmb.Text.Length - 1); } } } #endregion } #endregion }
https://w.atwiki.jp/kimikage/pages/60.html
似非ReadOnlyComboBox ※ComboBoxStyle.Simpleには未対応 using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; namespace WindowsFormsApplication1 { public partial class frmMain Form { private ReadOnlyComboBox cmb = new ReadOnlyComboBox(); private Button btn = new Button(); /// summary /// コンストラクタ /// /summary public frmMain() { InitializeComponent(); // 読み取り専用コンボの初期化 this.cmb.Location = new System.Drawing.Point(13, 13); cmb.Items.AddRange(new object[] { "にほん", "あめりか", "ちゅうごく" }); this.Controls.Add(this.cmb); // ReadOnly切替ボタンの初期化 this.btn.SetBounds(141, 9, 100, 24); this.btn.Text = "ReadOnly切替"; this.Controls.Add(this.btn); this.btn.Click += new System.EventHandler(this.btn_Click); } /// summary /// ReadOnly切替ボタンクリック /// /summary /// param name="sender" /param /// param name="e" /param private void btn_Click(object sender, EventArgs e) { this.cmb.ReadOnly = !this.cmb.ReadOnly; } } /// summary /// 読み取り専用プロパティありのコンボ /// (ComboBoxStyle.Simpleには未対応) /// /summary public class ReadOnlyComboBox ComboBox { private ReadOnlyComboButton cmbBtn; private ComboBoxStyle _ComboBoxStyle; private Boolean _ReadOnly; [Description("エディット コントロールの中の文字列を変更できるかどうかを設定します。ComboBoxStyle.Simpleには未対応")] [Category("動作")] [DefaultValue(false)] public Boolean ReadOnly { get { return _ReadOnly; } set { _ReadOnly = value; ReadOnlyChanged(); } } /// summary /// コンストラクタ /// /summary public ReadOnlyComboBox() { cmbBtn = new ReadOnlyComboButton(); ReadOnlyChanged(); cmbBtn.TabStop = false; this.Controls.Add(cmbBtn); } /// summary /// OnResize(Override) /// /summary /// param name="e" /param protected override void OnResize(EventArgs e) { cmbBtn.SetBounds(this.Width - 18, 1, 17, this.Height - 2); base.OnResize(e); } /// summary /// ReadOnlyが変更されたときの処理 /// /summary private void ReadOnlyChanged() { // 読み取り専用か? if (ReadOnly) { // 読み取り専用 _ComboBoxStyle = base.DropDownStyle; switch (base.DropDownStyle) { case ComboBoxStyle.DropDownList base.DropDownStyle = ComboBoxStyle.DropDown; this.BackColor = SystemColors.Control; cmbBtn.Visible = true; break; case ComboBoxStyle.DropDown this.BackColor = SystemColors.Control; cmbBtn.Visible = true; break; case ComboBoxStyle.Simple break; } } else { // 編集可能 cmbBtn.Visible = false; switch (_ComboBoxStyle) { case ComboBoxStyle.DropDownList base.DropDownStyle = _ComboBoxStyle; this.BackColor = SystemColors.Window; break; case ComboBoxStyle.DropDown this.BackColor = SystemColors.Window; break; case ComboBoxStyle.Simple break; } } } /// summary /// ProcessCmdKey(Override) /// /summary /// param name="msg" /param /// param name="keyData" /param /// returns /returns protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { // 読み取り専用か? if (ReadOnly) { // 特定のキー入力のみ許可 switch (keyData) { case (Keys.Control | Keys.C) case (Keys.Control | Keys.Left) case (Keys.Control | Keys.Right) case (Keys.Shift | Keys.Left) case (Keys.Shift | Keys.Right) case (Keys.Shift | Keys.Tab) case (Keys.Tab) case (Keys.Right) case (Keys.Left) case (Keys.Home) case (Keys.End) return base.ProcessCmdKey(ref msg, keyData); default return true; } } else { return base.ProcessCmdKey(ref msg, keyData); } } /// summary /// 読み取り専用コンボボタン /// /summary private class ReadOnlyComboButton Control { protected override void OnPaint(PaintEventArgs e) { ComboBoxRenderer.DrawDropDownButton(e.Graphics, new Rectangle(0, 0, this.Width, this.Height), System.Windows.Forms.VisualStyles.ComboBoxState.Normal); base.OnPaint(e); } } } }
https://w.atwiki.jp/memo77/pages/49.html
PageLastUpdate 2007-11-19/today - /yesterday - クリックすると見出し一覧を表示します DataGridViewEx comment DataGridViewEx DataGridViewの拡張クラス。まずは列の位置、幅、表示をユーザー設定として保存/読み出しするメソッドから。 読み出しを自動化したかったんですが、Newを拡張するとデザイナからの設定のほうが後なのでうまくいきません。 保存を自動化したかったんですが、DisposeだとすでにDataColumnが破棄されていてNothingを喰らいます(苦)。 LoadColumnStateはForm_Loadで、SaveColumnStateはForm_Closingで呼ぶのがよいでしょう。 誰かよいタイミングを知っていたら教えてください。 今後の予定 列の表示状態を制御できるなんらかのインターフェースの供給 CSVやTAB出力機能の供給 各機能のコンテキストメニューへの供給 など。なんかネタを振ってくれる人がいれば拡張するかもしれません。 Option Strict On Imports System.IO Public Class DataGridViewEx Inherits DataGridView Public Sub SaveColumnState() Try If Directory.Exists(Application.UserAppDataPath) = False Then Directory.CreateDirectory(Application.UserAppDataPath) End If Dim savepath As String = Path.Combine( _ Application.UserAppDataPath, _ "DataGridEx.ColumnState." Me.Name) Dim dt As New DataTable(Me.Name) dt.Columns.Add("Name", Type.GetType("System.String")) dt.Columns.Add("Width", Type.GetType("System.Int32")) dt.Columns.Add("DisplayIndex", Type.GetType("System.Int32")) dt.Columns.Add("Visible", Type.GetType("System.Boolean")) For Each Column As DataGridViewColumn In Me.Columns Dim row As DataRow = dt.NewRow row("Name") = Column.Name row("Width") = Column.Width row("DisplayIndex") = Column.DisplayIndex row("Visible") = Column.Visible dt.Rows.Add(row) Next dt.WriteXml(savepath) Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub Public Sub LoadColumnState() Try Dim loadpath As String = Path.Combine( _ Application.UserAppDataPath, _ "DataGridEx.ColumnState." Me.Name) If File.Exists(loadpath) = False Then Exit Sub Dim dt As New DataTable(Me.Name) dt.Columns.Add("Name", Type.GetType("System.String")) dt.Columns.Add("Width", Type.GetType("System.Int32")) dt.Columns.Add("DisplayIndex", Type.GetType("System.Int32")) dt.Columns.Add("Visible", Type.GetType("System.Boolean")) dt.ReadXml(loadpath) dt.DefaultView.Sort = "DisplayIndex" For Each drv As DataRowView In dt.DefaultView Dim column As DataGridViewColumn = Me.Columns(drv.Row("Name").ToString) column.DisplayIndex = CType(drv.Row("DisplayIndex"), Int32) column.Width = CType(drv.Row("Width"), Int32) column.Visible = CType(drv.Row("Visible"), Boolean) Next Catch ex As Exception MessageBox.Show(ex.ToString) End Try End Sub End Class comment このページの記述で聞きたいこととか間違ってることとかありましたらコメントを。 CSVやTAB出力機能の供給の予定は? -- (Tarou) 2008-01-11 11 54 43 こんにちは。手元にはあるんですがまだあげてませんね。来週にでも追加しときましょうか。 -- (memo77) 2008-01-11 12 29 51 名前 コメント すべてのコメントを見る