Eric R.
Eric R.

Reputation: 1125

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!

Upvotes: 0

Views: 5237

Answers (4)

afruzan
afruzan

Reputation: 1698

Use a ListCollectionView as source:

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

and then following function to add empty row if it is not appeared:

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

Upvotes: 0

Ben Petersen
Ben Petersen

Reputation: 506

I'm just starting to get this, but this has worked so far.

    <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>

Then to get the 'CanUserAddRows' to work, you need a default constructor in your ViewModel (where you do the bindings). If there is no default constructor, you won't get a blank row.

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

And in the actual Window, you have to set the DataContext for the DataGrid

public UserAlertWindow()
    {

        InitializeComponent();

        this.DataContext = new ViewModel.UserAlertWindowViewModel();
        UserAlertsGrid.DataContext = new ViewModel.UserAlertWindowViewModel(this);
    }

And for updating the database when the user edits or deletes, check this link, it looks very promising. http://www.dotnetcurry.com/ShowArticle.aspx?ID=566

Upvotes: 1

Haris Hasan
Haris Hasan

Reputation: 30097

Try setting CanUserAddRows to true of DataGrid

Upvotes: 0

OZnew
OZnew

Reputation: 58

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.

Upvotes: 1

Related Questions