当数据集为空时在 WPF DataGrid 中显示空白行

发布于 2024-12-18 17:59:12 字数 1327 浏览 0 评论 0原文

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

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

谢谢!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

梦里寻她 2024-12-25 17:59:12

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

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.

混浊又暗下来 2024-12-25 17:59:12

我刚刚开始明白这一点,但到目前为止这已经奏效了。

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

在实际的窗口中,您必须为 DataGrid 设置 DataContext

public UserAlertWindow()
    {

        InitializeComponent();

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

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

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

剪不断理还乱 2024-12-25 17:59:12

尝试将 DataGridCanUserAddRows 设置为 true

Try setting CanUserAddRows to true of DataGrid

仄言 2024-12-25 17:59:12

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

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();
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文