簡體   English   中英

C# WinForm DataGridView 添加未綁定的分欄符 CellFormatting

[英]C# WinForm DataGridView Adding Unbound Column Breaks CellFormatting

我有幾個 DataGridViews,它們使用 CellFormatting 事件處理程序將數據庫 ID 值轉換為用戶友好的顯示字符串。 但是,其中一個 DataGridViews 添加了 DataGridViewButtonColumn 以允許用戶對行數據執行一些數據分析。 問題:如果我在運行時將 Button 列添加到 DataGridView,網格將顯示原始數據庫 ID 值而不是用戶友好的字符串 ( 見圖1 )。 如果我注釋掉添加未綁定列的邏輯,網格將顯示用戶友好的字符串 ( 見圖2 )。

編輯:這是 CellFormatting 代碼:

private void GridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
   if (e.ColumnIndex == 1 && e.RowIndex >= 0 && e.Value != null)
   {
       int    experimentId = Convert.ToInt32(e.Value);
       string displayValue = ConvertToExperiment(experimentId);

       e.Value             = displayValue;
       e.FormattingApplied = true;
   }
}

這是添加按鈕列的初始化代碼:

private void LoadExperimentHistory()
{
    string selectCommand = "SELECT * FROM ExperimentLog";

    SQLiteCommand     sqlCommand     = new SQLiteCommand(selectCommand, databaseConnection);
    SQLiteDataAdapter sqlDataAdapter = new SQLiteDataAdapter(sqlCommand);

    DataSet dataSet = new DataSet();

    try
    {
        sqlDataAdapter.Fill(dataSet);
        historyDataTable = dataSet.Tables[0];

        if (historyDataTable != null)
        {
            dataGridView.DataSource = historyDataTable;
            dataGridView.Columns["ID"          ].Visible    = false;
            dataGridView.Columns["ExperimentId"].HeaderText = "Experiment";
            dataGridView.Columns["StartDate"   ].HeaderText = "Start Date";

            if (dataGridView.Columns["Analysis"] == null)
            {
                DataGridViewButtonColumn analysisColumn = new DataGridViewButtonColumn
                {
                    Name                        = "Analysis",
                    Text                        = "Run Analysis",
                    UseColumnTextForButtonValue = true,
                    FlatStyle                   = FlatStyle.Standard
                };

                analysisColumn.DefaultCellStyle.BackColor = Color.LightGray;
                dataGridView.Columns.Add(analysisColumn);
            }

        }
    }
    catch (Exception exception)
    {
        MessageForm messageForm = new MessageForm(exception.Message, MessageBoxButtons.OK);
        messageForm.ShowDialog();
    }
}

第二次編輯:

雖然我同意發布 CellFormatting() 代碼開始會有所幫助,但我仍然認為這是一個完全合理的問題/問題:為什么在世界上添加一個未綁定的列會破壞 CellFormatting() 中非常簡單的邏輯?

InitializeComponent()復制在設計時創建 DataGridView 的代碼

Form_Load()代碼中在運行時創建 DataGridView 的列。

列索引顯然是重疊的,並且更容易在一個地方解決它,並且在運行時為您提供更多控制。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM