我正在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();
}
如果有人可以帮助我解决此空行,以便用户输入数据,我将不胜感激!
谢谢!
也许您可以先检查源。如果从数据库获取的源为null,则将在GridView中添加新行。
我才刚开始得到这个,但是到目前为止已经奏效了。
<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
尝试将CanUserAddRows
的true
设置为DataGrid
使用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();
}
}
}