仅检索已修改的数据 - 复选框

时间:2015-10-02 14:12:13

标签: c# .net winforms checkbox

我有一个带复选框列的UltraGrid。

从Java中的Web方法初始化,该方法正在为数据调用DB。无论如何,当我运行应用程序时,一些复选框已经填满,我可以选中或取消选中。 我想检索已更新的列。目前,我做了一些允许我检索所有复选框状态的东西,而不仅仅是我修改过的复选框。

这是代码,方法GetStatusForRow检索复选框的状态,GetStatusCheckboxes调用前一个方法来获取所有复选框的状态。

public partial class FrmCVault : Form
{
    #region Properties

    /// <summary>
    /// Base filter lists
    /// </summary>
    //TODO: Change to a CVaultConfiguration Class
    public List<BASEFILTER> lBaseFilters { get; private set; }
    public List<SITE> lSites { get; private set; }
    public List<CONFIGURE> lConfigures{ get; private set; }

    #endregion

    #region Constructors

    /// <summary>
    /// Constructor
    /// </summary>
    public FrmCVault()
    {
        InitializeComponent();
        this.lBaseFilters = null;
        this.lSites = null;
        this.lConfigures = null;
    }

    #endregion

    #region Private methods

    #region Compare byte[]

    /// <summary>
    /// Compare two byte[]
    /// </summary>
    /// <param name="b1"></param>
    /// <param name="b2"></param>
    /// <returns></returns>
    private bool Compare(byte[] b1, byte[] b2)
    {
       // return Encoding.ASCII.GetString(b1) == Encoding.ASCII.GetString(b2);
        return b1.SequenceEqual(b2);
    }
    #endregion

    #region Fill the table with Basefilter data

    /// <summary>
    /// Fill the table with Basefilter data
    /// </summary>
    private void retrieveData()
    {
        EVPTProviderBase provider = DataRepository.EVPTProvider;

        ObjectDataSet ds = provider.GetBaseFilter();

        if (ds != null)
        {
            this.lBaseFilters = ds.arBASEFILTER.ToList();
            this.lSites = ds.arSITE.ToList();
            this.lConfigures = ds.arCONFIGURE.ToList();
        }
    }

    #endregion

    #region Load Base filter data from DB
    /// <summary>
    /// Load data from the database 
    /// </summary>
    private void LoadDataSource()
    {
        CVaultDataSource.Rows.Clear();

        if (this.lBaseFilters != null)
        {
            var filters = from filterBase in this.lBaseFilters
                          orderby filterBase.EVPTCODE
                          select new { Id = filterBase.ID, cvault = filterBase.CVAULTCODE, evpt = filterBase.EVPTCODE, desc = filterBase.EVPTDESIGNATION, duration = filterBase.DURATION, time = filterBase.ETDTIME };

            var sitesDB = from sites in this.lSites
                          orderby sites.KEY
                          select new { SiteKey = sites.KEY, SiteId = sites.ID };

            var configs = from config in this.lConfigures
                          select new { site = config.SITE_ID, baseF = config.BASEFILTER_ID };

            object[][] table = new object[filters.Count()][];
            int i = 0;

            foreach (var item in filters)
            {
                int j = 0;
                table[i] = new object[5 + sitesDB.Count()];
                table[i][j++] = item.cvault;
                table[i][j++] = item.evpt;
                table[i][j++] = item.desc;
                table[i][j++] = item.duration;
                table[i][j++] = item.time;
                foreach (var site in sitesDB)
                {
                    table[i][j] = false;

                    foreach (var conf in configs)
                    {
                        if (Compare(site.SiteId, conf.site) && Compare(conf.baseF, item.Id))
                        {
                            table[i][j] = true;
                            break;
                        }
                    }
                    j++;
                }
                i++;
            }
            foreach (var item in table)
            {
                CVaultDataSource.Rows.Add(item);
            }
        }
    }

    #endregion

    #region Add column sites

    /// <summary>
    /// Add columns in table according to the sites stored in DB
    /// </summary>
    /// <remarks>The action is used to create site column</remarks>
    private void AddColumnSites()
    {
        const string siteCol = "SITE_COL";

        var addNewSite = new Action<string>(site =>
        {
            if (siteCol != "OTHER") 
            {
                var ultraGridBand = this.CVaultGrid.DisplayLayout.Bands[0];

                var gridDataColumn = new UltraDataColumn(site);
                gridDataColumn.DataType = typeof(bool);
                gridDataColumn.Tag = siteCol;
                gridDataColumn.DataType = typeof(bool);
                gridDataColumn.DefaultValue = false;

                this.CVaultDataSource.Band.Columns.AddRange(new object[] {
                    gridDataColumn
                });
            }
        });

        for (int i = this.CVaultDataSource.Band.Columns.Count-1; i >= 0 ; i--)
        {
            if (this.CVaultDataSource.Band.Columns[i].Tag == siteCol)
            {
                this.CVaultDataSource.Band.Columns.RemoveAt(i);
            }
        }

        var sitesDB = from sites in this.lSites
                      orderby sites.KEY
                      select  sites.KEY ;

        foreach (var item in sitesDB)
        {
            addNewSite(item);
        }
    }

    #endregion

    #region Retrieve status of checkboxes
    /// <summary>
    /// Retrieve the checkboxes's status of  the last row selected
    /// </summary>
    /// <param name="b"></param>
    /// <param name="row"></param>
    /// <returns></returns>
    private Dictionary<string, bool> GetStatusForRow(UltraDataBand b, UltraDataRow row)
    {
        Dictionary<string, bool> statusChecked = new Dictionary<string, bool>();
        foreach (UltraDataColumn col in b.Columns.Cast<UltraDataColumn>()
                                         .Where(x => x.Tag != null &&
                                                x.Tag.ToString() == "SITE_COL"))
        {
            statusChecked.Add(col.Key, Convert.ToBoolean(row.GetCellValue(col)));
        }
        return statusChecked;
    }

    #endregion

    #region Retrieve status of hours columns

    private Dictionary<string, string> GetStatusHoursForRow(UltraDataBand b, UltraGridRow row)
    {
        Dictionary<string, string> statusChecked = new Dictionary<string, string>();
        foreach (UltraDataColumn col in b.Columns.Cast<UltraDataColumn>()
                                         .Where(x => x.Tag != null &&
                                                x.Tag.ToString() == "SITE_COL"))
        {
            //statusChecked.Add(,);
        }
        return statusChecked;
    }

    #endregion

    #endregion

    #region Form Events

    /// <summary>
    /// Form loading event
    /// </summary>
    /// <param name="sender">Form</param>
    /// <param name="e">Arguments (empty)</param>
    private void FrmCVault_Load(object sender, EventArgs e)
    {            
        this.retrieveData();
        this.AddColumnSites();
        this.LoadDataSource();
        CVaultGrid.DataBind();
    }

    private void ultraButton2_Click(object sender, EventArgs e)
    {
        CVaultGrid.ActiveRow.Update();
        CVaultGrid.DisplayLayout.Bands[0].AddNew();
    }

    private void FrmCVault_Shown(object sender, EventArgs e)
    {
        CVaultGrid.DisplayLayout.Bands[0].AddNew();
    }

    private void vl_ItemNotInList(object sender, ValidationErrorEventArgs e)
    {
        var ultrCombo = sender as UltraComboEditor;
        e.RetainFocus = true;

        if (e.LastValidValue != null)
            ultrCombo.Value = e.LastValidValue;
        else if (ultrCombo.Items.Count>0)
            ultrCombo.SelectedItem = ultrCombo.Items[0];
    }

    private void ultraGrid1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyData == Keys.Enter)
        {
            CVaultGrid.UpdateData();
        }
    }

    private void Cancel_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void SAVE_Click(object sender, System.EventArgs e)
    {
        this.GetStatusCheckboxes();
        this.GetStatusHours();
    }

    /// <summary>
    /// Get the status of checkboxes which have been changed (check or uncheck)
    /// </summary>
    private void GetStatusCheckboxes()
    {
        var statusChecked = new Dictionary<string, Dictionary<string, bool>>();
        foreach (UltraDataRow row in CVaultDataSource.Rows)
        {
            statusChecked.Add(row.GetCellValue(0).ToString(), GetStatusForRow(CVaultDataSource.Band, row));
        }

        foreach (KeyValuePair<string, Dictionary<string, bool>> kvp in statusChecked)
        {
            foreach (var sr in kvp.Value)
            {
                Console.WriteLine(string.Format("[{0}] Status site: {1} is {2}", kvp.Key, sr.Key, sr.Value));    
            }
        }

        Console.WriteLine("\r\n");
    }

    /// <summary>
    /// Get back the hour which have been updated
    /// From the column DURATION or ETD
    /// </summary>
    private void GetStatusHours()
    {
        //GetStatusHoursForRow(CVaultDataSource.Band, CVaultGrid.ActiveRow);
        //Dictionary<string, bool> statusChecked = GetStatusForRow(CVaultDataSource.Band, CVaultGrid.ActiveRow);
        //foreach (KeyValuePair<string, bool> kvp in statusChecked)
        //    Console.WriteLine("Status site:" + kvp.Key + " is " + kvp.Value.ToString());
        //Console.WriteLine("\r\n");
    }

    #endregion

    private void CVaultGrid_InitializeLayout(object sender, InitializeLayoutEventArgs e)
    {

    }
}

这是一个看窗口的屏幕:

Example of window

1 个答案:

答案 0 :(得分:0)

最好检查整行的状态,以查看列的CheckBox是否为SET,拦截ITS EVENT,如:

Public Sub dataGridView1_CellValueChanged(ByVal sender As Object, _
ByVal e As DataGridViewCellEventArgs) _
Handles dataGridView1.CellValueChanged

If dataGridView1.Columns(e.ColumnIndex).Name = "MyCheckBox" Then
    Dim checkCell As DataGridViewCheckBoxCell = _
        CType(dataGridView1.Rows(e.RowIndex).Cells("MyCheckBox"), _
        DataGridViewCheckBoxCell)

    Dim IsSet as boolean = checkCell.Value

    dataGridView1.Invalidate()
End If

End Sub