gpt4 book ai didi

c# - 单元格值不会改变 DataGridview

转载 作者:行者123 更新时间:2023-11-29 23:57:44 37 4
gpt4 key购买 nike

我正在使用 EF6/MySQL 来填充 DataGridView。我需要将列的值(0 或 1)转换为相应的值(“蓝色”或“绿色”),并更改其样式。以下代码执行时不会出错,但单元格不会更改。

 using (var db = new hyperion_paymenttrackerEntities())
{
dgvTracker.Rows.Clear();
// Goal = Convert.ToDecimal(db.configs.Where(o => o.Name == "goal").Select(o => o.Value).FirstOrDefault());
var data = from c in db.payments.AsEnumerable()
select new
{
c.CollectorName,
c.Lead,
c.C2ndTalkOff,
c.PaymentType,
c.PaymentAmount
};
dgvTracker.DataSource = data.ToList();
}
var dataGridViewColumn = dgvTracker.Columns["CollectorName"];
if (dataGridViewColumn != null)
dataGridViewColumn.HeaderText = "Collector";
var gridViewColumn = dgvTracker.Columns["Lead"];
if (gridViewColumn != null) gridViewColumn.HeaderText = "Generated By";
var viewColumn = dgvTracker.Columns["C2ndTalkOff"];
if (viewColumn != null) viewColumn.HeaderText = "Assisted By";
var column = dgvTracker.Columns["PaymentType"];
if (column != null) column.HeaderText = "Type";
var dataGridViewColumn1 = dgvTracker.Columns["PaymentAmount"];
if (dataGridViewColumn1 != null)
dataGridViewColumn1.HeaderText = "Payment Amount";


//blue = 0 green = 1
foreach (DataGridViewRow row in dgvTracker.Rows)
{
var cell = row.Cells["PaymentType"];
if ((string) cell.Value == "0")
{
cell.Style = BlueStyle();
cell.Value = "BLUE";
}
else
{
cell.Style = GreenStyle();
cell.Value = "GREEN";
}
}

最佳答案

我认为 DataGridViewCellFormatting(...) 事件可能更有效,因为这就是该事件的用途。尝试这样的事情:

    private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)    
{
if (e.ColumnIndex == 1 ) // Change int value of '1' to the Column you want to edit
{
if (!ReferenceEquals(e.Value, DBNull.Value)) // You don't need this check if you are not doing any conversion of the e.Value to a numeric value.
{
if (e.Value.ToString() == "0") // Change colour and value to blue.
{
// Use this lines to change the color of just the cell
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.Blue;
style.ForeColor = Color.White;
style.Font = new System.Drawing.Font("Arial", 10, FontStyle.Regular);
e.CellStyle = style;
e.Value = "BLUE";
}
if (e.Value.ToString() == "1") // Change colour and value to green
{
// Use this lines to change the color of just the cell
DataGridViewCellStyle style = new DataGridViewCellStyle();
style.BackColor = Color.Green;
style.ForeColor = Color.White;
style.Font = new System.Drawing.Font("Arial", 10, FontStyle.Regular);
e.CellStyle = style;
e.Value = "GREEN";
}
}
}
}

希望对您有所帮助。

关于c# - 单元格值不会改变 DataGridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25230611/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com