[英]How to import selected columns and rows of excel file to listView c#
[英]C# Listview diffrent colors rows and columns
我試圖在列表視圖上添加不同的 colors 行和列。
首先我使用了這些代碼
foreach (ListViewItem item in listView.Items)
{
item.BackColor = item.Index % 2 == 0 ? Color.FromArgb(70, 70, 70) : Color.FromArgb(61, 61, 61);
}
然后我嘗試了這些代碼:
foreach (ListViewItem item in listView.Items)
{
item.SubItems[2].BackColor = Color.FromArgb(18, 64, 100);
item.SubItems[9].BackColor = Color.FromArgb(105, 16, 38);
item.UseItemStyleForSubItems = false;
}
怎么了?
謝謝你。
當您應用交替行 colors 時,您僅將其應用於第 1 列(也稱為item
)。 當您應用列 [2 和 9] 格式時,您關閉UseItemStyleForSubItems
,因此現在只有第一列帶有交替行 colors。您必須將交替行和列格式代碼組合到一個代碼塊中,如下所示:
foreach (ListViewItem item in listView.Items)
{
//Disable item styles for sub items so we can apply column colors.
item.UseItemStyleForSubItems = false;
//Create the main colors used for row formatting.
Color a = Color.FromArgb(61, 61, 61);
Color b = Color.FromArgb(70, 70, 70);
//Create the alternate colors used for column 2 and 9.
Color alt2 = Color.FromArgb(18, 64, 100);
Color alt9 = Color.FromArgb(105, 16, 38);
//Apply colors to column 1
if (item.Index % 2 == 0) {
item.BackColor = b;
} else {
item.BackColor = a;
}
//Loop through the sub items and apply colors.
foreach(ListViewSubItem sub in item.SubItems) {
if (sub.Index == 2) { //Apply column 2 color.
sub.BackColor = alt2;
} else if (sub.Index == 9) { //Apply column 9 color.
sub.BackColor = alt9;
} else if (item.Index % 2 == 0) { //Apply alt row color.
sub.BackColor = b;
} else { //Apply main row color. This is the default.
sub.BackColor = a;
}
}
}
我用這個代碼做了。
foreach (ListViewItem item in listView.Items)
{
//Disable item styles for sub items so we can apply column colors.
item.UseItemStyleForSubItems = false;
//Create the main colors used for row formatting.
Color a = Color.FromArgb(61, 61, 61);
Color b = Color.FromArgb(70, 70, 70);
//Create the alternate colors used for column 2 and 9.
Color alt2 = Color.FromArgb(18, 64, 100);
Color alt9 = Color.FromArgb(105, 16, 38);
//Apply colors to column 1
if (item.Index % 2 == 0)
{
item.BackColor = b;
}
else
{
item.BackColor = a;
}
int i = 0;
foreach (ListViewSubItem sub in item.SubItems)
{
sub.Name = i.ToString();
i++;
}
foreach (ListViewSubItem sub in item.SubItems)
{
if (sub.Name == "3")
{ //Apply column 2 color.
sub.BackColor = alt2;
}
else if (sub.Name == "11")
{ //Apply column 9 color.
sub.BackColor = alt9;
}
else if (item.Index % 2 == 0)
{ //Apply alt row color.
sub.BackColor = b;
}
else
{ //Apply main row color. This is the default.
sub.BackColor = a;
}
}
listView.Sort();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.