asp:FileUploadを使用せずにファイルをアップロードする[IE,C#]

asp:FileUploadを使わずにファイルをダウンロード・アップロードするには、System.Net.WebClientを使います。

    System.Net.WebClient webc = new System.Net.WebClient();
    webc.DownloadFile(downloadFileUrl, localFilePath);
    webc.UploadFile(uploadFileUrl, localFilePath);

アップロード先のaspでは、Requestの内容をファイルに書き込む処理を書く必要ありです。

コメントする

要素のスタイルを文字列で取得する[IE,Javascript]

IE8の場合、要素のスタイルは、その要素のcurrentStyleとstyle.cssTextを足したものになる。
currentStyleがCSSを解決したもので、style.cssTextはタグに直接指定されたスタイルの文字列になる。
タグで直接指定したスタイルはcurrentStyleには入らないところがなんとも。

function getStyleString()
{
    var cssText = "";
    for( var item in element.currentStyle)
    {
        var itemcv = item.replace(/[A-Z]/g,function(whole,p1){return ("-" + item.charAt(p1).toLowerCase())});
        cssText += itemcv + ":" + element.currentStyle.getAttribute(item) + ";";
    }
    cssText += element.style.cssText;
    
    return cssText;
}

コメントする

ASP.NETのページにHiddenFieldを動的に作成する[ASP.NET,C#]

ASP.NETのページにHiddenFieldを動的に作るには、HiddenFieldオブジェクトを作成してフォームのコントロールのコレクションにAddすればいい。

    HiddenField dynamicHiddenField = new HiddenField();
    dynamicHiddenField.ID = "idString";
    dynamicHiddenField.Value = "test value";
    form.Controls.Add(dynamicHiddenField);

コメントする

Excelの参照を追加せずにExcelを使う[C#]

C#でExcelを扱う場合、参照にCOMオブジェクトを追加すれば使うことができるが、開発環境のExcelのバージョンに依存してしまうため、環境が異なる場合は動作しなくなる。
この問題は、Type.GetTypeFromProgID()でクラスタイプを解決し、Activator.CreateInstance()でインスタンスを作る、という方法で解決できる。

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace temp
{
    // Excel Wrapper Class
    public class ExcelWrapper : IDisposable
    {
        const int PARAM_NUM_1 = 1;   // パラメータ数(1)
        const int PARAM_NUM_2 = 2;   // パラメータ数(2)
        const int PARAM_NUM_3 = 3;   // パラメータ数(3)
        const int PARAM_NUM_4 = 4;   // パラメータ数(4)
        const int PARAM_NUM_5 = 5;   // パラメータ数(5)
        const int PARAM_NUM_6 = 6;   // パラメータ数(6)
        const int PARAM_NUM_7 = 7;   // パラメータ数(7)
        const int PARAM_NUM_8 = 8;   // パラメータ数(8)
        const int PARAM_NUM_9 = 9;   // パラメータ数(9)
        const int PARAM_NUM_10 = 10; // パラメータ数(10)
        const int PARAM_NUM_11 = 11; // パラメータ数(11)
        const int PARAM_NUM_12 = 12; // パラメータ数(12)
        const int PARAM_NUM_13 = 13; // パラメータ数(13)
        const int PARAM_NUM_14 = 14; // パラメータ数(14)
        const int PARAM_NUM_15 = 15; // パラメータ数(15)
        const int PARAM_NUM_16 = 16; // パラメータ数(16)
        const int PARAM_NUM_17 = 17; // パラメータ数(17)
        const int PARAM_NUM_18 = 18; // パラメータ数(18)
        const int PARAM_NUM_19 = 19; // パラメータ数(19)
        const int PARAM_NUM_20 = 20; // パラメータ数(20)
        const int PARAM_NUM_21 = 21; // パラメータ数(21)
        const int PARAM_NUM_22 = 22; // パラメータ数(22)
        const int PARAM_NUM_23 = 23; // パラメータ数(23)
        const int PARAM_NUM_24 = 24; // パラメータ数(24)
        const int PARAM_NUM_25 = 25; // パラメータ数(25)
        const int PARAM_NUM_26 = 26; // パラメータ数(26)
        const int PARAM_NUM_27 = 27; // パラメータ数(27)
        const int PARAM_NUM_28 = 28; // パラメータ数(28)
        const int PARAM_NUM_29 = 29; // パラメータ数(29)
        const int PARAM_NUM_30 = 30; // パラメータ数(30)
        const int PARAM_NUM_31 = 31; // パラメータ数(31)
        const int PARAM_NUM_32 = 32; // パラメータ数(32)
        const int PARAM_NUM_33 = 33; // パラメータ数(33)
        const int PARAM_NUM_34 = 34; // パラメータ数(34)
        const int PARAM_NUM_35 = 35; // パラメータ数(35)
        const int PARAM_NUM_36 = 36; // パラメータ数(36)

        // Excelアプリケーションオブジェクト
        private object xlsApplication = null;
        // Workbooksオブジェクト
        private object xlsBooks = null;

        // Excelアプリケーションオブジェクト
        protected object XlsApplication
        {
            get
            {
                // 存在しない場合は作成する
                if (xlsApplication == null)
                {
                    Type classType = Type.GetTypeFromProgID("Excel.Application");
                    xlsApplication = Activator.CreateInstance(classType);
                }
                return xlsApplication;
            }
        }
        // バージョン
        public string Version
        {
            get
            {
                object versionObj = XlsApplication.GetType().InvokeMember("Version", BindingFlags.GetProperty, null, XlsApplication, null);
                return versionObj.ToString();
            }
        }
        // 保存時の確認メッセージ有効
        public bool DisplayAlerts
        {
            set
            {
                object[] parameters = new object[PARAM_NUM_1];
                parameters[0] = value;
                XlsApplication.GetType().InvokeMember("DisplayAlerts", BindingFlags.SetProperty, null, XlsApplication, parameters);
            }
        }
        // アプリケーション可視
        public bool Visible
        {
            set
            {
                object[] parameters = new object[PARAM_NUM_1];
                parameters[0] = value;
                XlsApplication.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, XlsApplication, parameters);
            }
        }
        // Workbooksオブジェクト
        protected object Workbooks
        {
            get
            {
                if (xlsBooks == null)
                {
                    xlsBooks = XlsApplication.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, XlsApplication, null);
                }
                return xlsBooks;
            }
        }
        // 破棄
        public void Dispose()
        {
            ReleaseComObject(xlsBooks);
            xlsBooks = null;
            ReleaseComObject(xlsApplication);
            xlsApplication = null;
        }
        // COMオブジェクトのリリース
        private static void ReleaseComObject(object target)
        {
            try
            {
                if ((target != null))
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(target);
                }
            }
            finally
            {
                target = null;
            }
        }
        // Bookを取得
        private object GetBook(int index)
        {
            object[] parameters = new object[PARAM_NUM_1];
            parameters[0] = index;
            return Workbooks.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, Workbooks, parameters);
        }
        // Sheetsを取得
        private object GetSheets(object book)
        {
            return book.GetType().InvokeMember("Worksheets", BindingFlags.GetProperty, null, book, null);
        }
        // Sheetを取得
        private object GetSheet(object sheets, string sheetName)
        {
            object[] parameters = new object[PARAM_NUM_1];
            parameters[0] = sheetName;
            return sheets.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, sheets, parameters);
        }
        // Rangeを取得
        private object GetRange(object sheet, string range)
        {
            object[] parameters = new Object[PARAM_NUM_2];
            parameters[0] = range;
            parameters[1] = Type.Missing;
            return sheet.GetType().InvokeMember("Range", BindingFlags.GetProperty, null, sheet, parameters);
        }
        // Cellsを取得
        private object GetCells(object sheet)
        {
            return sheet.GetType().InvokeMember("Cells", BindingFlags.GetProperty, null, sheet, null);
        }
        // Cellを取得
        private object GetCell(object cells, int row, int column)
        {
            object[] parameters = new Object[PARAM_NUM_2];
            parameters[0] = row;
            parameters[1] = column;
            return cells.GetType().InvokeMember("Item", BindingFlags.GetProperty, null, cells, parameters);
        }

        private object GetCellText(object cell)
        {
            return cell.GetType().InvokeMember("Text", BindingFlags.GetProperty, null, cell, null);
        }
        // Cellのテキストを取得
        private void SetCellText(object cell, string value)
        {
            object[] parameters = new Object[PARAM_NUM_1];
            parameters[0] = value;
            cell.GetType().InvokeMember("Value", BindingFlags.SetProperty, null, cell, parameters);
        }
        // Excelファイルを開く
        public void Open(string xlsFilePath)
        {
            object[] parameters = new object[PARAM_NUM_15];
            parameters[0] = xlsFilePath;
            parameters[1] = Type.Missing;
            parameters[2] = Type.Missing;
            parameters[3] = Type.Missing;
            parameters[4] = Type.Missing;
            parameters[5] = Type.Missing;
            parameters[6] = Type.Missing;
            parameters[7] = Type.Missing;
            parameters[8] = Type.Missing;
            parameters[9] = Type.Missing;
            parameters[10] = Type.Missing;
            parameters[11] = Type.Missing;
            parameters[12] = Type.Missing;
            parameters[13] = Type.Missing;
            parameters[14] = Type.Missing;
            Workbooks.GetType().InvokeMember("Open", BindingFlags.InvokeMethod, null, Workbooks, parameters);
        }
        // マクロを起動
        public void Run(string bookName, string methodName)
        {
            object[] parameters = new object[PARAM_NUM_31];
            parameters[0] = "'" + bookName + "'!" + methodName;
            parameters[1] = Type.Missing;
            parameters[2] = Type.Missing;
            parameters[3] = Type.Missing;
            parameters[4] = Type.Missing;
            parameters[5] = Type.Missing;
            parameters[6] = Type.Missing;
            parameters[7] = Type.Missing;
            parameters[8] = Type.Missing;
            parameters[9] = Type.Missing;
            parameters[10] = Type.Missing;
            parameters[11] = Type.Missing;
            parameters[12] = Type.Missing;
            parameters[13] = Type.Missing;
            parameters[14] = Type.Missing;
            parameters[15] = Type.Missing;
            parameters[16] = Type.Missing;
            parameters[17] = Type.Missing;
            parameters[18] = Type.Missing;
            parameters[19] = Type.Missing;
            parameters[20] = Type.Missing;
            parameters[21] = Type.Missing;
            parameters[22] = Type.Missing;
            parameters[23] = Type.Missing;
            parameters[24] = Type.Missing;
            parameters[25] = Type.Missing;
            parameters[26] = Type.Missing;
            parameters[27] = Type.Missing;
            parameters[28] = Type.Missing;
            parameters[29] = Type.Missing;
            parameters[30] = Type.Missing;
            XlsApplication.GetType().InvokeMember("Run", BindingFlags.InvokeMethod, null, XlsApplication, parameters);
        }
        // マクロを起動
        public void Run(string bookName, string methodName, string param1, string param2)
        {
            object[] parameters = new object[PARAM_NUM_31];
            parameters[0] = "'" + bookName + "'!" + methodName;
            parameters[1] = param1;
            parameters[2] = param2;
            parameters[3] = Type.Missing;
            parameters[4] = Type.Missing;
            parameters[5] = Type.Missing;
            parameters[6] = Type.Missing;
            parameters[7] = Type.Missing;
            parameters[8] = Type.Missing;
            parameters[9] = Type.Missing;
            parameters[10] = Type.Missing;
            parameters[11] = Type.Missing;
            parameters[12] = Type.Missing;
            parameters[13] = Type.Missing;
            parameters[14] = Type.Missing;
            parameters[15] = Type.Missing;
            parameters[16] = Type.Missing;
            parameters[17] = Type.Missing;
            parameters[18] = Type.Missing;
            parameters[19] = Type.Missing;
            parameters[20] = Type.Missing;
            parameters[21] = Type.Missing;
            parameters[22] = Type.Missing;
            parameters[23] = Type.Missing;
            parameters[24] = Type.Missing;
            parameters[25] = Type.Missing;
            parameters[26] = Type.Missing;
            parameters[27] = Type.Missing;
            parameters[28] = Type.Missing;
            parameters[29] = Type.Missing;
            parameters[30] = Type.Missing;
            XlsApplication.GetType().InvokeMember("Run", BindingFlags.InvokeMethod, null, XlsApplication, parameters);
        }
        // Excel終了
        public void Quit()
        {
            XlsApplication.GetType().InvokeMember("Quit", BindingFlags.InvokeMethod, null, XlsApplication, null);
        }
        // 保存
        public void Save(int bookIndex)
        {
            object book = null;

            try
            {
                // WorkbooksオブジェクトからBookオブジェクトを取得
                book = GetBook(bookIndex);

                // ブックを保存
                book.GetType().InvokeMember("Save", BindingFlags.InvokeMethod, null, book, null);
            }
            finally
            {
                ReleaseComObject(book);
            }
        }
        // Cellの値を文字列で取得
        public string GetCellValue(int bookIndex, string sheetName, int row, int column)
        {
            object book = null;
            object sheets = null;
            object sheet = null;
            object cells = null;
            object cell = null;

            try
            {
                // WorkbooksオブジェクトからBookオブジェクトを取得
                book = GetBook(bookIndex);

                // BookオブジェクトからSheetsオブジェクトを取得
                sheets = GetSheets(book);

                // SheetsオブジェクトからSheetオブジェクトを取得
                sheet = GetSheet(sheets, sheetName);

                // SheetオブジェクトからCellsオブジェクトを取得
                cells = GetCells(sheet);

                // CellsオブジェクトからCellオブジェクトを取得
                cell = GetCell(cells, row, column);

                // CellオブジェクトからTextを取得
                object text = GetCellText(cell);

                return text.ToString();
            }
            finally
            {
                ReleaseComObject(cell);
                ReleaseComObject(cells);
                ReleaseComObject(sheet);
                ReleaseComObject(sheets);
                ReleaseComObject(book);
            }
        }
        // Cellに値を設定
        public void SetCellValue(int bookIndex, string sheetName, int row, int column, string value)
        {
            object book = null;
            object sheets = null;
            object sheet = null;
            object cells = null;
            object cell = null;

            try
            {
                // WorkbooksオブジェクトからBookオブジェクトを取得
                book = GetBook(bookIndex);

                // BookオブジェクトからSheetsオブジェクトを取得
                sheets = GetSheets(book);

                // SheetsオブジェクトからSheetオブジェクトを取得
                sheet = GetSheet(sheets, sheetName);

                // SheetオブジェクトからCellsオブジェクトを取得
                cells = GetCells(sheet);

                // CellsオブジェクトからCellオブジェクトを取得
                cell = GetCell(cells, row, column);

                // Cellオブジェクトに値を設定
                SetCellText(cell, value);
            }
            finally
            {
                ReleaseComObject(cell);
                ReleaseComObject(cells);
                ReleaseComObject(sheet);
                ReleaseComObject(sheets);
                ReleaseComObject(book);
            }
        }
        // 最終行のIndexを取得
        public int GetLastRowIndex(int bookIndex, string sheetName)
        {
            object book = null;
            object sheets = null;
            object sheet = null;
            object cells = null;
            object specialCells = null;

            try
            {
                // WorkbooksオブジェクトからBookオブジェクトを取得
                book = GetBook(bookIndex);

                // BookオブジェクトからSheetsオブジェクトを取得
                sheets = GetSheets(book);

                // SheetsオブジェクトからSheetオブジェクトを取得
                sheet = GetSheet(sheets, sheetName);

                // SheetオブジェクトからCellsオブジェクトを取得
                cells = GetCells(sheet);

                // Cellsオブジェクトから最終行Indexを取得
                object[] parameters = new object[PARAM_NUM_2];
                parameters[0] = 11; //xlCellTypeLastCell
                parameters[1] = Type.Missing;
                specialCells = cells.GetType().InvokeMember("SpecialCells", BindingFlags.InvokeMethod, null, cells, parameters);
                return (int)specialCells.GetType().InvokeMember("Row", BindingFlags.GetProperty, null, specialCells, null);
            }
            finally
            {
                ReleaseComObject(specialCells);
                ReleaseComObject(cells);
                ReleaseComObject(sheet);
                ReleaseComObject(sheets);
                ReleaseComObject(book);
            }
        }
        // 最終列のIndexを取得
        public int GetLastColumnIndex(int bookIndex, string sheetName)
        {
            object book = null;
            object sheets = null;
            object sheet = null;
            object cells = null;
            object specialCells = null;

            try
            {
                // WorkbooksオブジェクトからBookオブジェクトを取得
                book = GetBook(bookIndex);

                // BookオブジェクトからSheetsオブジェクトを取得
                sheets = GetSheets(book);

                // SheetsオブジェクトからSheetオブジェクトを取得
                sheet = GetSheet(sheets, sheetName);

                // SheetオブジェクトからCellsオブジェクトを取得
                cells = GetCells(sheet);

                // Cellsオブジェクトから最終行Indexを取得
                object[] parameters = new object[PARAM_NUM_2];
                parameters[0] = 11; //xlCellTypeLastCell
                parameters[1] = Type.Missing;
                specialCells = cells.GetType().InvokeMember("SpecialCells", BindingFlags.InvokeMethod, null, cells, parameters);
                return (int)specialCells.GetType().InvokeMember("Column", BindingFlags.GetProperty, null, specialCells, null);
            }
            finally
            {
                ReleaseComObject(specialCells);
                ReleaseComObject(cells);
                ReleaseComObject(sheet);
                ReleaseComObject(sheets);
                ReleaseComObject(book);
            }
        }
    }
}

コメントする

DataGridViewで単一選択のチェックボックスを作る[C#]

DataGridViewにチェックボックスを配置することは、けっこう簡単にできますが、ラジオボタンを配置することは難しいです。できるんですか?
そこで、チェックボックスを単一選択にしてラジオボタンのかわりにしてしまおうと。

チェックボックスの配置は簡単にできますが、これを単一選択にするようなメソッドもプロパティもありません。
そこで、チェックボックスのイベントを捕まえてなんとかしようとするわけですが、ちょっとコツがあります。
チェックされたチェックボックスにReadOnlyを設定するのです。チェックされていないチェックボックスはReadOnlyを解除しておきます。
これで余計なイベントの発生が防げます。

// チェックボックスのCellValueChangedイベント
private void dataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    // 選択列の場合
    if (e.ColumnIndex == 0)
    {
        // 今回チェック設定した
        if ((bool)dataGridView[e.ColumnIndex, e.RowIndex].Value == true)
        {
            // 他にチェックされている項目がある場合はそのチェックを解除
            for (int rowIndex = 0; rowIndex < dataGridView.Rows.Count; rowIndex++)
            {
                if ((rowIndex != e.RowIndex) && ((bool)dataGridView[0, rowIndex].Value == true))
                {
                    // チェックを解除
                    dataGridView[0, rowIndex].Value = false;
                    // ReadOnlyを解除
                    dataGridView[0, rowIndex].ReadOnly = false;
                }
            }
            // 今回チェックした場所をReadOnlyに設定
            dataGridView[e.ColumnIndex, e.RowIndex].ReadOnly = true;
        }
    }
}

コメントする

テーブルを空読みする[SQL]

フィールド名のコレクションが欲しいだけとか、Insertするための空のテーブルが欲しいとき、

SELECT * FROM TABLENAME WHERE 0=1

とすると、余計な検索を行わずに空のテーブルが取得できます。
“WHERE 0=1″が大事なところですよ。

コメントする

列がIDENTITYかどうか調べる[SQL Server]

列のIDENTITYの状態は、クエリの結果からDataColumn#AutoIncrementで取得できそうですが、できません。

システムDBのsys.columnsから取得できます。

SELECT name,column_id,is_identity from sys.columns where object_Id = OBJECT_ID('[TableName]','U') order by column_id

[TableName]の部分は任意のテーブル名に置き換えてください。

コメントする

WebService経由で取得したオブジェクトをXMLにシリアライズ。Postback先でデシリアライズできない[ASP.NET,C#]

クライアント側でWebService経由で取得したオブジェクトをXMLにシリアライズして、サーバにPostbackしてデシリアライズすると、エラーにはならないが、内容が復元できていないことがある。
これは、クライアント側はWebServiceのWeb参照に変換されたクラスでシリアライズされ、これにWebServiceのnamespaceが付与されるためである。このため、サーバ側でデシリアライズに使用するクラスに同じnamespaceが設定されていないと、内容がまったく復元されない。
これを解決するために、サーバ側で使用するクラスにWebServiceと同じnamespaceを付与する。

コメントする

DataGridViewで入力できるコンボボックスを1セルだけ作る[C#]

DataGridViewに入力できるコンボボックスを1セルだけ作成する。
入力されたアイテムがコンボボックス内のリストになければ、コンボボックス内のリストの先頭に追加する。

これを実現するために、DataGridViewのEditingControlShowingイベントとCellValidatingイベントでいろいろする必要がある。

EditingControlShowingイベントは、編集用のコンボボックスが作成され表示される直前にコールされる。
DataGridViewの場合はDataGridViewComboBoxEditingControlが作成されるが、このコントロールのDropDownStyleをComboBoxStyle.DropDownに変更する。これでコンボボックスへの入力は可能となるが、入力した内容がリストに追加されない。
リストへの追加はCellValidatingイベントで行う。

CellValidatingイベントはセルがフォーカスを失う時にコールされる。
このとき、入力された文字列がコンボボックス内のリストにない場合は、リストに追加する必要がある。

さらに、最終セルの場合(例えば3×3のリストで右下のセル)は入力後のEnterキーでCellValidatingイベントが発生しない。これはカレントのセルが遷移しないため。これを解決するためにEnterキーのイベントでカレントセルを一度クリアし、再度設定してCellValidatingイベントを発生させる。

以下、サンプルソース。

// フォームのロードでDataGridViewを初期化
private void Form1_Load(object sender, EventArgs e)
{
    // 列を追加
    dataGridView1.Columns.Add("aaaa", "aaaa");
    dataGridView1.Columns.Add("bbbb", "bbbb");
    dataGridView1.Columns.Add("cccc", "cccc");

    // 行を追加
    dataGridView1.Rows.Add();
    dataGridView1.Rows.Add();
    dataGridView1.Rows.Add();

    // DataGridView全体を編集可能にする
    dataGridView1.ReadOnly = false;
    // 3x3の一番右下のセルを入力できるコンボボックスにする。
    dataGridView1[2, 2] = new DataGridViewComboBoxCell();
    dataGridView1[2, 2].ReadOnly = false; // 編集可能に設定

    // コンボボックスにアイテムを追加する
    ((DataGridViewComboBoxCell)dataGridView1[2, 2]).Items.Add("あああ");
    ((DataGridViewComboBoxCell)dataGridView1[2, 2]).Items.Add("いいい");
    ((DataGridViewComboBoxCell)dataGridView1[2, 2]).Items.Add("ううう");
    ((DataGridViewComboBoxCell)dataGridView1[2, 2]).Items.Add("えええ");
    ((DataGridViewComboBoxCell)dataGridView1[2, 2]).Items.Add("おおお");
}

// DataGridViewのEditingControlShowingイベントを処理する
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    // コントロールがDataGridViewComboBoxEditingControlの場合
    if (e.Control is DataGridViewComboBoxEditingControl)
    {
        // 該当位置のセルの場合
        if ((dgv.CurrentCell.RowIndex == 2) && (dgv.CurrentCell.ColumnIndex == 2))
        {
            // DropDownStyleをドロップダウンに変更
            ((DataGridViewComboBoxEditingControl)e.Control).DropDownStyle = ComboBoxStyle.DropDown;
            // Enrerキーイベントを捕まえるためのイベントを登録
            ((DataGridViewComboBoxEditingControl)e.Control).PreviewKeyDown += new PreviewKeyDownEventHandler(Form1_PreviewKeyDown);
        }
    }
}

// DataGridViewComboBoxEditingControlのキーイベントを処理する
void Form1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
    // Enterキーの場合
    if (e.KeyCode == Keys.Enter)
    {
        // カレントセルをバックアップ
        DataGridViewCell curCell = ((DataGridViewComboBoxEditingControl)sender).EditingControlDataGridView.CurrentCell;
        // カレントセルをクリア
        ((DataGridViewComboBoxEditingControl)sender).EditingControlDataGridView.CurrentCell = null;
        // カレントセルを再設定(これでCellValidatingイベントが発行される)
        ((DataGridViewComboBoxEditingControl)sender).EditingControlDataGridView.CurrentCell = curCell;
    }
}

// CellValidatingイベントを処理する
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    // 該当位置のセルの場合
    if ((dgv.CurrentCell.RowIndex == 2) && (dgv.CurrentCell.ColumnIndex == 2))
    {
        // コンボボックス内のリストを更新
        UpdateCmbList(dgv.CurrentCell.ColumnIndex, dgv.CurrentCell.RowIndex, e.FormattedValue, ref this.dataGridView1);
    }
}

// コンボボックス内のリストを更新する
private void UpdateCmbList(int colIndex, int rowIndex, object value, ref DataGridView dgv)
{
    bool delete = false;
    bool add = false;

    // 値を文字列に変換
    string formattedValue = string.Empty;
    if (value != null)
    {
        formattedValue = value.ToString();
    }
    // リストの項目数が選択項目より多い場合は先頭の項目を削除
    if (((DataGridViewComboBoxCell)dgv.Rows[rowIndex].Cells[colIndex]).Items.Count > 5)
    {
        // 先頭の項目が今回入力した文字列でない場合は削除を予約
        // ここで削除すると、セルのValueをまだ変更していないので例外が発生する。
        // セルのValueを変更後にリストから削除する。
        if (((DataGridViewComboBoxCell)dgv.Rows[rowIndex].Cells[colIndex]).Items[0].ToString() != formattedValue)
        {
            delete = true;
        }
    }
    // 値がリストに存在するか確認
    if (((DataGridViewComboBoxCell)dgv.Rows[rowIndex].Cells[colIndex]).Items.Contains(formattedValue) != true)
    {
        // 存在しない場合は先頭に追加
        ((DataGridViewComboBoxCell)dgv.Rows[rowIndex].Cells[colIndex]).Items.Insert(0, formattedValue);
        add = true;
    }
    // 一度コミットする(リストへの追加を有効にするため)
    dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
    // セルのValueを更新
    ((DataGridViewComboBoxCell)dgv.Rows[rowIndex].Cells[colIndex]).Value = formattedValue;
    // リストから削除
    if (delete == true)
    {
        int index = 0;
        if (add == true)
        {
            index = 1;
        }
        ((DataGridViewComboBoxCell)dgv.Rows[rowIndex].Cells[colIndex]).Items.RemoveAt(index);
    }
    // もう一度コミットする
    dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

コメントする

ASP.NETでHiddenFieldの値が取得できない[ASP.NET]

ASP.NETでHiddenFieldに格納したはずの値がPostbackで取得できなくて3時間くらいはまりました。
JavascriptでHiddenFieldに値を格納する場合は、”value”の先頭文字は小文字です。

コメントする

過去の投稿 »
フォロー

Get every new post delivered to your Inbox.