DataGridView

如何将数据库添加进DataGridView?

将查询的数据用DataTable存储。

例如 DataTable dt;数据存在dt对象中

DataGirdView.DataSource=dt;

这样就把数据存在了DataGridView.

在Columns中 需要将Data一栏中的DataPropertyName与数据库中的列名相同完成绑定。

例如 显示班别,需要将名字改为Shift(即数据库中的列名).

显示的时候,没有按照Edit Columns中的顺序显示怎么做?

 DataGirdView.AutoGenerateColumns = false;

可以使顺序正常。

DataGridView不仅可以接受DataTable 也可以接收List 它接受的是一个对象.

增加序号。

int coun = grdData.RowCount;
for (int i = 0; i < coun - 1; i++)
{
grdData.Rows[i].Cells["RowID"].Value = i + 1;//引号中为列名
}

将DataTable中某列的数据修改成想要的

for (int j = 0; j < dt.Rows.Count; j++)
            {
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[j]["Ref_Status"].ToString().Equals(""))
                    {
                        strRefStatus = "EMPTY";
                    }
                    else
                    {
                        strRefStatus = dt.Rows[j]["Ref_Status"].ToString();//每行状态值赋值给strRefStatus
                    }
                    if (strRefStatus != "FULL")
                    {
                        strStatus = "";
                        if (strRefStatus == "EMPTY")
                        {
                            strStatus = "备料";
                        }
                        if (strStatus == "PREPARE")
                        {
                            strStatus = "备料中";
                        }
                        if (strRefStatus == "WAIT")
                        {
                            strStatus = "等待";
                        }
                    }
                }
                grdData.Rows[j].Cells["Status"].Value = strStatus;
            }
View Code

根据10进制颜色代码赋值BackColor

首先将10进制数转成16进制数,后加上#和 添加0完成赋值。

six = int.Parse(strColorgrid);//强制转换int
varcolor = Convert.ToString(six, 16);//转换成16进制
count = varcolor.Length;
if (count < 6)
{
for (int j = 0; j < 6 - count; j++)
{
varcolor = varcolor + "0";
}
}
grdData.Rows[i].Cells[1].Style.BackColor = ColorTranslator.FromHtml("#" + varcolor);
View Code

DataGridView 每行的颜色交替显示

//设置表格背景色
grdData.RowsDefaultCellStyle.BackColor = Color.White;
//设置交替行的背景色
grdData.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua;

 数据量庞大的时候使用双缓冲,可以加快滚动条拖动速度。

public void SetDataGridViewDB(System.Windows.Forms.DataGridView dataGridView)
        {
            Type dgvType = dataGridView.GetType();
            System.Reflection.PropertyInfo pi = dgvType.GetProperty("DoubleBuffered",
                System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            pi.SetValue(dataGridView, true, null);
        }
View Code
原文地址:https://www.cnblogs.com/cdjbolg/p/11756887.html