我嘗試使用以下條件更改背景顏色。它不起作用。
private void frmJobStat_Load(object sender, EventArgs e)
{
sql = "SELECT `jobno` AS JOB_NO,`lcode` AS LOCATION,iscompleted, iscannotrepair, isissued FROM `jobmaster`";
config.Load_DTG(sql, dgvJobNo);
dgvJobNo.Columns[1].Visible = false;
//dgvJobNo.Columns[2].Visible = false;
//dgvJobNo.Columns[3].Visible = false;
//dgvJobNo.Columns[4].Visible = false;
dgvJobNo.Columns[0].Width = 100;
dgvJobNo.DefaultCellStyle.Format = "000000";
for (int i = 0; i < dgvJobNo.Rows.Count - 1; i )
{
if (Boolean.Parse(dgvJobNo.Rows[i].Cells[2].Value.ToString()))
{
dgvJobNo.Rows[i].DefaultCellStyle.BackColor = Color.Blue;
}
}
//foreach (DataGridViewRow rw in dgvJobNo.Rows)
//{
// if (rw.Cells[2].Value.ToString()=="1")
// {
// dgvJobNo.DefaultCellStyle.BackColor = Color.Red;
// }
//}
}
我從具有真/假值的表中加載了一列。當顏色為真時,我需要更改顏色。
誰能幫我?
uj5u.com熱心網友回復:
使用 DataGridView 的人經常傾向于直接擺弄單元格以及值的顯示方式。使用 DataBinding 更容易:使用 將資料與其顯示方式分開DataGridView.DataSource。
使用資料源
我對您在 DataGridView 中顯示的內容一無所知,因此假設您想顯示產品。
所以在某處你有一個類可以從某個地方保存和檢索產品。當然,你隱藏了資料是從資料庫中獲取的,以及它是如何獲取的(DbConnection 和 DbCommand?或者物體框架和 LINQ?)。您所知道的是,您可以存盤產品并在以后檢索它們:
interface IRepository
{
int AddProduct(Product product) // returns Id
Product FetchProduct(int id);
IEnumerable<Product> FetchProducts(...); // fetches several Products to display
...
哦,在我忘記之前:
class Product
{
public int Id {get; set;}
public string Name {get; set;}
public decimal Price {get; set;}
public int Stock {get; set;}
...
}
假設您有一個帶有 DataGridView 的表單,您想在其中顯示一些產品。使用 Visual Studio 設計器,您添加了一個 DataGridView 和一些列
在建構式中:
public MyForm : ...
{
InitializeComponent();
this.columnId.DataPropertyName = nameof(Product.Id);
this.columnName.DataPropertyName = nameof(Product.Name);
this.columnPrice.DataPropertyName = nameof(Product.Price);
...
}
當然,您可以訪問存盤庫和獲取您想要顯示的產品的方法:
private IRepository ProductRepository => ...
private IEnumerable<Product> FetchProductsToDisplay()
{
return this.ProductRepository.FetchProducts(...);
}
現在要顯示獲取的產品,我們在 BindingList 中使用 DataGridView 的資料源:
private BindingList<Product> DisplayedProducts
{
get => (BindingList<Product>)this.dataGridView1.DataSource;
set => this.dataGridView1.DataSource = value;
}
private void ShowInitialProducts()
{
this.DisplayedProducts = new BindingList<Product>( this.FetchProductsToDisplay().ToList());
當然,在加載表單時:
private void OnFormLoading(object sender, ...)
{
this.ShowInitialProducts();
}
這足以顯示所有產品。如果操作員添加或洗掉一些行,或編輯行的值,它們會自動更新。如果操作員指示他已完成編輯產品,例如通過單擊“確定”按鈕:
private void OnButtonOkClicked(object sender, ...)
{
this.ProcessEditedProducts();
}
private void ProcessEditedProducts()
{
ICollection<Product> displayedProducts = this.DisplayedProducts();
// find out which Products are added / removed / changed
this.ProcessProducts(displayedProducts);
}
順便說一句,你有沒有注意到我的程式總是很小:它們只做一件事,服務于一個目的。這使它們易于理解、易于重用、易于測驗和更改。
間奏曲:一些有用的功能
The following small methods might be handy. If you have a DataGridViewRow, you can get DataGridViewRow.DataBoundItem to get the Product that is shown in the Row.
// Get the Product that is displayed in row with rowIndex
private Product DisplayedProduct(int rowIndex)
{
return (Product)this.dataGridView1.Rows[rowIndex].DataBoundItem;
}
// Get the Currently Selected Product
private Product CurrentProduct()
{
return (Product)this.dataGridView1.CurrentRow.DataBoundItem;
}
// Get all Selected Products (if you allow multi-selecting
private IEnumerable<Product> GetSelectedProducts()
{
return this.dataGridView1.SelectedRows.Cast<DataGridViewRow>()
.Select(row => row.DataBoundItem)
.Cast<Product>();
}
Back to your question
Apparently, there is a predicate which makes that you want to give some Cells a different background Color. For example: if the stock is zero, you want it red, and if the stock is low, you want it orange. Otherwise you want a white background
Color ZeroStockColor = Color.Red;
Color LowStockColor = Color.Orange;
int LowStockValue = 10; // 10 or less: Stock is low
Just before the value of a cell is displayed, you get the chance to format the cell, using event DataGridView.CellFormatting.
If the column that shows the Stock is being formatted, we want to check the Value of the Stock. If it is zero, we want red background, if it is low, we have an orange background.
private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
// e contains the rowIndex and columnIndex
if (e.ColumnIndex = this.columnStockValue.Index)
{
// Formatting the cell that contains the stock value
Product productToFormat = this.DisplayedProduct(e.RowIndex);
DataGridViewCell cellToFormat = this.dataGridView1
.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (productToFormat.Stock == 0)
{
// no stock: RED!
cellToFormat.Style.BackColor = ZeroStockColor;
}
else if (productToFormat.Stock <= LowStockValue)
{
// Low stock: Orange!
cellToFormat.Style.BackColor = LowStockColor;
}
else
{
// enough stock: use default cell Style of this column
cellToFormat.Style = null;
}
}
}
如果 aDataGridViewCell.Style不為空,則此樣式用于設定單元格的格式。如果 Style 為 null,則DataGridViewColumn.DefaultCellStyle使用 ,除非該值也為 null。在這種情況下,我們會走得更高:DataGridView.DefaultCellStyle
結論
如果您使用 DataBinding,則很容易在 DataGridView 中顯示您的資料并訪問 DataGridView 中的物件:當前物件、選定物件或顯示在第 10 行中的物件。
要格式化單元格,請DataGridViewCell.Style在列或 DataGridView 中使用或 DefaultCellStyle
使用事件DataGridView.CellFormatting在單元格顯示之前格式化單元格。
uj5u.com熱心網友回復:
這是行不通的,因為在 C# 中,如果您僅通過賦值創建一個新物件,它將不會生成子參考,因此
dgvJobNo.Rows[i].DefaultCellStyle.BackColor
這里可能不存在。
你必須做這樣的事情
for (int i = 0; i < dgvJobNo.Rows.Count - 1; i )
{
if (Boolean.Parse(dgvJobNo.Rows[i].Cells[2].Value.ToString()))
{
var row= new Rows();
var a = new DefaultCellStyle();
a.BackColor= Color.Blue;
row.DefaultCellStyle = a;
dgvJobNo.Rows[i] = row;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/332916.html
上一篇:WinFormsChart中的實時心電圖資料c#問題
下一篇:無法更改TextBox文本
