【问题标题】:Get active datagrid's name upon cell editing event?在单元格编辑事件时获取活动数据网格的名称?
【发布时间】:2016-06-14 10:53:14
【问题描述】:

我一直试图在单元格编辑事件中获取活动数据网格的名称。

首先,我不知道这是否是一个好习惯,但我有一个在编辑数据网格的单元格时运行的事件。然后我试图测试用户是否在表中添加了一行。我想要一种方法来查看正在编辑哪个表,以便我可以放入一个 if 子句将其定向到正确的代码,这样它就不会引发错误。

private void DataGrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {

            Staff_Time_TBL selectedRow = e.Row.Item as Staff_Time_TBL;
            long id = selectedRow.ID;

            if (id == -1)
            {
                // give a GUID and then insert it into the database when saved
                selectedRow.ID = DateTime.UtcNow.Ticks;
                sql.Staff_Time_TBLs.InsertOnSubmit(selectedRow);
            }

            try
            {
                sql.SubmitChanges();
                LastSavedTextBlock.Text = "Last saved: " + DateTime.Now.ToLongTimeString();
            }
            catch(Exception ex)
            {
                Alerts.Error("Couldn't save changed to the database", "Database Error", ex);
            }
        }

目前,很明显如果下面代码中的这个表不被访问就会抛出错误,

Staff_Time_TBL selectedRow = e.Row.Item as Staff_Time_TBL;
                long id = selectedRow.ID;

我尝试获取数据网格的名称,这只是返回 DataGrid

var tblName = sender.GetType().Name;

这会为变量tblName2 返回null,并因此在最后一行引发异常。

string dataGridName = "";             
            DataObject tblName2 = sender as DataObject;
            dataGridName = tblName2.ToString();

this thread 获取所有表名,This thread 检查是否存在,但我找不到任何有关如何获取 sender 数据网格名称的信息。

显然,如果这不是好的做法,我想知道。谢谢。

【问题讨论】:

    标签: c# wpf datagrid


    【解决方案1】:

    使用VisualTreeHelper类:

    private void Dgrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
            {
                FrameworkElement source = e.EditingElement;
    
                while (!(source is DataGrid))
                    source = VisualTreeHelper.GetParent(source) as FrameworkElement;
    
                MessageBox.Show(((DataGrid)source).Name);
            }
    

    【讨论】:

    • 如果不是数据网格会抛出错误吗?谢谢
    【解决方案2】:

    如果它是您想要的数据网格的名称,这应该可以。

    DataGrid dg = (DataGrid)sender;  // Will throw an exception if not a DataGrid
    string name = dg.Name;
    

    不知道你为什么使用 DataObject。

    【讨论】:

    • Datagrid 不在智能感知中。那是我认为我需要的,但 b/c 它不存在,我通过一大堆控件和对象来实现它。我有很多东西要学。
    • 现在我意识到你可以做到这一点,为了解决你可以做到这一点的例外情况,DataGrid dg = sender as DataGrid; if (dg != null) { string dgName = dg.Name; }
    • 这完全取决于你是否想要例外。有时你会,有时你不会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多