Search code examples
c#wpfdatagridwpfdatagrid

Show Blank Row In WPF DataGrid when DataSet is Empty


I am running an SQL query on a SQL Server 2008 database. The results from this query are displayed in a WPF DataGrid. My code works great, except when the dataset is empty. I want the user to be able to add new rows, but when the dataset is empty there is no empty row for the user to enter data into. Below is my code:

        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();
        }

If anybody can help me out with getting this empty row so the user can enter data, I would greatly appreciate it!

Thanks!


Solution

  • Maybe you can check the source first. if source you get from database is null, then you will add a new row into the GridView.