根据值C#更改datagridview行的颜色 [英] Change color of datagridview row depending on value C#
问题描述
我有datagridview,其中包含6列产品ID,产品名称,功能,价格,数量和总价。数量为0的所有产品将自动从数据网格视图中删除。我的问题是如何在数量中更改单元格的颜色如果:
1.如果数量少于20色橙色
2.如果数量小于10红色
请耐心等我,因为我是编程新手。我需要为我们为顶点项目制作的库存系统执行此操作。
非常感谢!
我尝试了什么:
我不知道从哪里开始,但这是我们用于datagrdiview1的代码:
I have datagridview which is populated with 6 columns product id,product name,features,price,quantity and total price. All product with 0 quantity is automatically removed from the datagridview. My questions is how do I change color of the cell in "Quantity" if:
1. If quantity is less than 20 color orange
2. If quantity is less than 10 color red
Please bear with me as I am new to programming. I am required to do this for the inventory system we made for our capstone project.
Many thanks!
What I have tried:
I have no idea where to start but this is the code we used for datagrdiview1:
public void GetData()
{
try
{
con = new SqlConnection(cs.DBConn);
con.Open();
String sql = "SELECT Product.ProductID,ProductName,Features,Price,sum(Quantity),sum(Price*Quantity) from Temp_Stock,Product where Temp_Stock.ProductID=Product.ProductID group by Product.productID,productname,Price,Features,Quantity having(Quantity>0) order by ProductName";
cmd = new SqlCommand(sql, con);
rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
dataGridView1.Rows.Clear();
while (rdr.Read() == true)
{
dataGridView1.Rows.Add(rdr[0], rdr[1], rdr[2], rdr[3], rdr[4], rdr[5]);
}
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
推荐答案
尝试
try
int columnIndex = 4; // quantity column , zero based index
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int quantity;
if (int.TryParse(row.Cells[columnIndex].Value.ToString(), out quantity))
{
if (quantity < 20)
row.Cells[columnIndex].Style.BackColor = System.Drawing.Color.Red;
if (quantity < 10)
row.Cells[columnIndex].Style.BackColor = System.Drawing.Color.Orange;
}
}
您可以使用 GridView.RowDataBound Event(System.Web.UI.WebControls) [ ^ $
You can use GridView.RowDataBound Event (System.Web.UI.WebControls)[^]
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TableCell cell = e.Row.Cells[4];
int quantity = int.Parse(cell.Text);
if (quantity < 20)
{
cell.BackColor = Color.Orange;
}
if (quantity < 10)
{
cell.BackColor = Color.Red;
}
}
}
这篇关于根据值C#更改datagridview行的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!