可能重复:
如果一行不为空,c#更改颜色
我的表中有一些值,我对如何更改它有一些疑问:
1.如果“KundeID”不是空的紫罗兰色,我想改变背景,我试过--->
foreach (DataGridViewRow row1 in dataGridView2.Rows)
{
if (row1.Cells[2].Value != null)
{
row1.DefaultCellStyle.BackColor = Color.Violet;
}
}
但它给我所有的桌子上色
2.我想在对象 6 中有两个 X,
object[] o5 = { 6, "XX", "Sprite"+"Jogurt" }; table.Rows.Add(o6);
当我有 2 个“产品”并想在我的表中显示它时,不知道如何
我的表:
KundeID KundeName Comment Jogurt Fanta Sprite
1 Michael "nichts" x //violet
2 Raj "Ich bin cool" //violet
Gary "yahoo" x
Miky x
5 MM x //violet
(6 XX x x) // Want to do two X's, violet
我的代码:
DataTable table = new DataTable("Kunde");
table.Columns.Add("KundeID", typeof(Int32));
table.Columns.Add("KundeName", typeof(String));
table.Columns.Add("Produkt", typeof(String));
DataTable comment = new DataTable("Comment");
comment.Columns.Add("KundeName", typeof(String));
comment.Columns.Add("Comment", typeof(String));
DataSet ds = new DataSet("DataSet");
ds.Tables.Add(table);
ds.Tables.Add(comment);
object[] o1 = { 1, "Michael", "Jogurt" };
object[] o2 = { 2, "Raj" };
object[] o3 = { null, "Gary", "Fanta" };
object[] o4 = { null, "Miky", "Sprite" };
object[] o5 = { 5, "MM", "Sprite" };
object[] c1 = { "Raj", "Ich bin cool" };
object[] c2 = { "Gary", "yahoo" };
object[] c3 = { "Michael", "nichts" };
table.Rows.Add(o1);
table.Rows.Add(o2);
table.Rows.Add(o3);
table.Rows.Add(o4);
table.Rows.Add(o5);
comment.Rows.Add(c1);
comment.Rows.Add(c2);
comment.Rows.Add(c3);
var results = from table1 in table.AsEnumerable()
join table2 in comment.AsEnumerable()
on table1.Field<string>("KundeName") equals table2.Field<string>("KundeName") into prodGroup
from table4 in prodGroup.DefaultIfEmpty()
select new
{
KundeID = table1.Field<Int32?>("KundeID"),
KundeName = table1.Field<String>("KundeName"),
Produkt = table1.Field<String>("Produkt"),
Comment = table4 != null ? table4.Field<String>("Comment") : null,
};
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var result = new DataTable();
result.Columns.Add("KundeID", typeof(Int32));
result.Columns.Add("KundeName", typeof(String));
result.Columns.Add("Comment", typeof(String));
result.Columns.AddRange(
(from c in
(from r in table.AsEnumerable()
where !r.IsNull("Produkt") && !string.IsNullOrEmpty(r.Field<string>("Produkt"))
select r.Field<string>("Produkt")).Distinct()
select new DataColumn(c, typeof(bool))).ToArray()
);
foreach (var r in results)
{
var productIndex = result.Columns.IndexOf(r.Produkt);
var vals = new List<object>() { r.KundeID, r.KundeName, r.Comment };
for (int i = 3; i < result.Columns.Count; i++)
{
if (i == productIndex)
{
vals.Add(true);
}
else
{
vals.Add(false);
}
}
result.LoadDataRow(vals.ToArray(), true);
}
dataGridView2.DataSource = result ;
//Here will change all background to violet, I want just some of them
//foreach (DataGridViewRow row1 in dataGridView2.Rows)
//{
// if (row1.Cells[2].Value != null)
// {
// row1.DefaultCellStyle.BackColor = Color.Violet;
// }
//}
}