我在Wpf DataGrid. I am adding values in datagrid's first column called
型号名称中遇到问题。下面我也给我的代码来说明问题。
所以我的问题是第一列将显示数据库中的值,其他列可以写入。所有值都将保存在某些数据库表中。当我使用datagrid.Items.Add(data);
然后它在第一列中给出值,工作正常但如果我开始在其他列中写入它会给出错误
“不允许使用Edititem”。
这是我在WPF中的代码
<DataGrid HorizontalAlignment="Center"
Name="DeliveryGrid" IsReadOnly="False"
AutoGenerateColumns="False"
LoadingRow="DataGrid_LoadingRow"
Margin="0,85,0,0"
VerticalAlignment="Top"
Height="235"
Width="462">
<DataGrid.Columns>
<DataGridTextColumn Header="Model" Width="90" Binding="{Binding ModelName}" x:Name="ModelName" />
<DataGridTextColumn Header="Engine No" Width="90" x:Name="EngineNo" />
<DataGridTextColumn Header="Chasis No" Width="90" x:Name="ChasisNo" />
<DataGridTextColumn Header="Authority No" Width="90" x:Name="AuthorityNo" />
<DataGridTextColumn Header="Price" x:Name="Price" />
</DataGrid.Columns>
</DataGrid>
这是我在C#中的代码
public class BikesOrderObjects
{
public string ModelName { get; set; }
public int ModelID { get; set; }
public string BEngineNo { get; set; }
public string BChasisNo { get; set; }
public string BAuthorityNo { get; set; }
public double Price { get; set; }
public int qty { get; set; }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
RST_DBDataContext conn = new RST_DBDataContext();
LoadDeliveryData();
}
private void LoadDeliveryData()
{
RST_DBDataContext conn = new RST_DBDataContext();
var BikesOrderData = conn.TblBikesOrdersDetails
.Where(TblBikesOrdersDetail => TblBikesOrdersDetail.BOId == 1)
.Select(TblBikesOrdersDetail => new
{
qty = TblBikesOrdersDetail.BQty,
ModelID = TblBikesOrdersDetail.ModelId,
ModelName = TblBikesOrdersDetail.TblBikeModel.ModelName
});
foreach (var item in BikesOrderData)
{
for (int i = 0; i < item.qty; i++)
{
var data = new BikesOrderObjects { ModelName = item.ModelName };
DeliveryGrid.Items.Add(data);
}
}
}
答案 0 :(得分:2)
您should not update the Items
直接DataGrid
,而是将ItemsSource
设置为实现IEditableCollectionView
界面的集合,以便进行编辑。此界面具有功能EditItems()
,可以进行编辑。
所以为了解决这个问题。在窗口中创建ObservableCollection<BikesOrderObjects>
属性说MyBikesOrders并将DataGrid ItemsSource
绑定到它
<DataGrid HorizontalAlignment="Center" ItemsSource="{Binding MyBikesOrders}"/>
假设您已将窗口的DataContext
设置为自身。
在构造函数中,您可以通过新建它来初始化此集合,并在LoadDeliveryData
方法中将对象添加到此集合中。
答案 1 :(得分:0)
我的解决方案是我的代码
private void LoadDeliveryData()
{
RST_DBDataContext conn = new RST_DBDataContext();
var BikesOrderData = conn.TblBikesOrdersDetails
.Where(TblBikesOrdersDetail => TblBikesOrdersDetail.BOId == 1)
.Select(TblBikesOrdersDetail => new
{
qty = TblBikesOrdersDetail.BQty,
ModelID = TblBikesOrdersDetail.ModelId,
ModelName = TblBikesOrdersDetail.TblBikeModel.ModelName
});
List<BikesOrderObjects> data = new List<BikesOrderObjects>();
foreach (var item in BikesOrderData)
{
for (int i = 0; i < item.qty; i++)
{
BikesOrderObjects datae = new BikesOrderObjects();
datae.ModelName = item.ModelName;
data.Add(datae);
}
}
DeliveryGrid.ItemsSource = data;
}