【问题标题】:Show Blank Row In WPF DataGrid when DataSet is Empty当 DataSet 为空时,在 WPF DataGrid 中显示空白行
【发布时间】:2011-11-29 04:38:23
【问题描述】:

我正在 SQL Server 2008 数据库上运行 SQL 查询。此查询的结果显示在 WPF DataGrid 中。我的代码运行良好,除非数据集为空。我希望用户能够添加新行,但是当数据集为空时,没有空行供用户输入数据。以下是我的代码:

        try
        {
            string accountQuery = "SELECT a.AccountName AS 'Account Name', a.AccountDesc AS 'Account Description', " +
                "a.AccountNumber AS 'Account #', b.AccountType AS 'Account Type', c.AccountName AS 'Account Parent' " +
                "FROM Accounts AS a INNER JOIN AccountType AS b ON a.AccountTypeID = b.AccountTypeID " +
                "LEFT OUTER JOIN Accounts AS c ON c.AccountID = a.AccountParentID " +
                "WHERE a.UserID = " + currentUserID;

            SqlDataReader accounts = null;
            SqlCommand query = new SqlCommand(accountQuery, dbConnection);

            accounts = query.ExecuteReader();

            DataTable accountsTable = new DataTable();
            accountsTable.Load(accounts);

            this.GridAccounts.ItemsSource = accountsTable.DefaultView;

            accounts.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);

            // Close the DB if there was an error.
            if (dbConnection.State == ConnectionState.Open)
                dbConnection.Close();
        }

如果有人可以帮助我获取这个空行以便用户输入数据,我将不胜感激!

谢谢!

【问题讨论】:

    标签: c# wpf datagrid wpfdatagrid


    【解决方案1】:

    也许你可以先检查一下来源。如果您从数据库获取的源为空,那么您将在 GridView 中添加一个新行。

    【讨论】:

    • 也许你可以试试这个 dataTable.Rows.Add(dataTable.NewRow());
    • 我认为这是针对 winforms 的。 WPF 数据网格中没有可添加行的 Rows 属性。
    • Rows 属性不是用于 DataGrid,而是用于 DataTable
    • 我能够做到这一点,现在唯一的问题是我有空白行并且我有空白行供用户添加数据。所以,我有两个空白行。
    • 我只是想到了一个解决方法。如果我的数据集中没有行,我将手动添加一个,并将 CanUserAddRows 更改为 false。然后我只有一个空行。一旦用户将有效数据添加到该行,我将再次将 CanUserAddRows 更改为 true 并保持这种状态。感谢您的帮助!
    【解决方案2】:

    我刚刚开始了解这个,但到目前为止它已经奏效了。

        <DataGrid CanUserAddRows="True" CanUserDeleteRows="True" ItemsSource="{Binding UserAlerts}" IsSynchronizedWithCurrentItem="True" x:Name="UserAlertsGrid">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Node ID" Binding="{Binding Node_id}"></DataGridTextColumn>
                <DataGridTextColumn Header="Threshold" Binding="{Binding Threshold}"></DataGridTextColumn>
                <DataGridTextColumn Header="Type of Alert" Binding="{Binding TypeOfAlert}"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>
    

    然后,要让“CanUserAddRows”工作,您需要在 ViewModel 中使用默认构造函数(在其中进行绑定)。如果没有默认构造函数,你不会得到一个空白行。

        class UserAlertViewModel : BaseViewModel
    {
        private readonly UserAlert _alertItem;
    
        public UserAlertViewModel()
        {
            _alertItem = new UserAlert();
        }
    
        public UserAlertViewModel(UserAlert alertItem)
        {
            _alertItem = alertItem;
        }
        public int Node_id
        {
            get { return _alertItem.Node_id; }
            set { _alertItem.Node_id = value; OnPropertyChanged("Node_id"); }
        }
        public double Threshold
        {
            get { return _alertItem.Threshold; }
            set { _alertItem.Threshold = value; OnPropertyChanged("Threshold"); }
        }
        public string TypeOfAlert
        {
            get { return _alertItem.TypeOfAlert; }
            set { _alertItem.TypeOfAlert = value; OnPropertyChanged("TypeOfAlert"); }
        }
    }
    

    在实际的Window中,你必须为DataGrid设置DataContext

    public UserAlertWindow()
        {
    
            InitializeComponent();
    
            this.DataContext = new ViewModel.UserAlertWindowViewModel();
            UserAlertsGrid.DataContext = new ViewModel.UserAlertWindowViewModel(this);
        }
    

    对于在用户编辑或删除时更新数据库,请查看此链接,它看起来很有希望。 http://www.dotnetcurry.com/ShowArticle.aspx?ID=566

    【讨论】:

      【解决方案3】:

      尝试将CanUserAddRows 设置为trueDataGrid

      【讨论】:

        【解决方案4】:

        使用ListCollectionView 作为来源:

        datagrid.CanUserAddRows = true;
        datagrid.ItemsSource = new ListCollectionView(items_list);
        

        如果没有出现空行,则添加以下函数:

        public void AddNewRow()
        {
            if (datagrid.Items is System.ComponentModel.IEditableCollectionViewAddNewItem items)
            {
                if (!items.IsAddingNew)
                {
                    items.AddNew();
                }
            }
        }
        

        【讨论】: