c# - 设置datagridview的数据源后添加单元格值
问题描述
DataGridview
从数据库中获得后DataSource
,我尝试以两种方式添加列:设计Tax
和Discount
代码。但是当我运行这段代码时:
public void LoadGridView()
{
GrdReceiptDetail.AutoGenerateColumns = false;
GrdReceiptDetail.DataSource = SentoDB.usp_viewReceiptDetail(ReceiptId);
foreach (DataGridViewColumn column in GrdReceiptDetail.Columns)
{
if (column.Name != "Check" && column.Name != "Tax" && column.Name != "Discount")
{
GrdReceiptDetail.Columns[column.Index].ReadOnly = true;
}
}
foreach (DataGridViewRow row in GrdReceiptDetail.Rows)
{
if (row.Index != 0)
{
GrdReceiptDetail.Rows[row.Index].Cells["Discount"].Value = "10";
GrdReceiptDetail.Rows[row.Index].Cells["Tax"].Value = "10";
}
}
}
在我加载表格后,第 2 列的单元格中的值Discount
是Tax
空白的。我该如何解决?我认为当我使用 时DataSource
,可能会DataGridview
阻止我添加列和值。
解决方案
尝试这个..
if (row.Index != 0)
{
//replace RowObject with the name of your underlying class that constitutes each
//row
RowObject obj = (RowObject)row.DataBoundItem;
//replace DiscountProperty and TaxProperty with the names of the properties on
//your RowObject that correspond to these values
obj.DiscountProperty = "10";
obj.TaxProperty = "10";
}
希望这对你有用。这是一个类似问题的链接,详细说明了为什么在使用基础数据源修改 DataGridView 时应该以这种方式更新数据。 以编程方式在数据网格视图中设置单元格值
推荐阅读
- java - 如何用jdbc实现一对多
- python - 在单个序列化程序 django 中读取和创建嵌套关系
- php - Atom 编辑器:如何为 php 以不同的方式突出显示单引号和双引号字符串
- express - 如何在猫鼬中添加多个模型?
- pine-script - 如何突出显示计算/值等于两个价格/水平之间的位置?
- uber-api - 无法在悉尼获得 UberPool
- python - 如何在python中为多个散点图制作一个循环?
- image - 如何更改图像中的像素值范围?
- javascript - 移动浏览器分享链接问题
- python - 在 python 3 中使用 pip 导入运行时安装的模块