搬家第14天-136.Wincc V7.3 使用c脚本将数据表内容放在ListView控件中
以前联系过使用vbs将数据库Report下数据表的内容放入控件Listview中。今天练习了使用c脚本实现同样的功能。在数据库Report下有一个数据表,表结构如下:
表中已经有以下内容
变量管理下新建4个8位文本变量,名字分别为CurDate,flow1,flow2,flow3,分别用来存放数据库几个字段数值。在画面上放置一个listview控件,名字修改为LV,放置一个按钮,按钮的鼠标点击事件中添加以下c脚本
#include "apdefap.h"
void OnClick(char* lpszPictureName, char* lpszObjectName, char* lpszPropertyName)
{
#pragma code("kernel32.dll")
#define GetObject GetObject
int i,RsCount;
__object *pdl=NULL;
__object *pic=NULL;
__object *obj=NULL;
__object *ListItem=NULL;
__object *ListSubItem=NULL;
__object *cn=NULL;
__object *rs=NULL;
char *connstr="Provider = SQLOLEDB.1;password = sa;user id = sa;Initial Catalog =Report;Data Source=.\\WINCC";
char sql[256];
pdl = __object_create("PDLRuntime");
pic=pdl->GetPicture("");
obj=pic->GetObject("LV");
cn=__object_create("ADODB.Connection");
rs=__object_create("ADODB.RecordSet");
sprintf(sql,"%s","select CurDate,Convert(varchar(10),flow1),Convert(varchar(10),flow2),Convert(varchar(10),flow3) from report" );
cn->open(connstr);
if (cn->State == 0)// 为0表示连接数据库不成功
MessageBox(NULL,"连接数据库失败!","警告",MB_OK);
else
{
rs->Open(sql,cn,3,1);
RsCount=rs->RecordCount;
rs->MoveFirst();
//初始化ListView表头
obj->View =3; //设置外观为报表形式
obj->GridLines =TRUE; //显示网格线
obj->labeledit=TRUE;
obj->checkboxes=TRUE;
obj->AllowColumnReorder =TRUE;
obj->ColumnHeaders->Clear(); //清除原有表头
//表头制作
for(i=0;i<=4;i++)
obj->ColumnHeaders->Add();
obj->ColumnHeaders->item(1)->width=20;
obj->ColumnHeaders->item(2)->text="日期";
obj->ColumnHeaders->item(2)->width=80;
obj->ColumnHeaders->item(3)->text="流量1";
obj->ColumnHeaders->item(3)->width=120;
obj->ColumnHeaders->item(4)->text="流量2";
obj->ColumnHeaders->item(4)->width=150;
obj->ColumnHeaders->item(5)->text="流量3";
obj->ColumnHeaders->item(5)->width=180;
//表格填入数据
obj->listitems->Clear(); //清除原有数据
for (i=1;i<=RsCount;i++)
{
//将数据表字段存放在内部字符串变量里面
SetTagChar("CurDate",rs->fields(0)->value);
SetTagChar("flow1",rs->fields(1)->value);
SetTagChar("flow2",rs->fields(2)->value);
SetTagChar("flow3",rs->fields(3)->value);
ListItem=obj->ListItems->add();//添加一行
//添加日期
ListSubItem=ListItem->ListSubItems->add();
ListSubItem->text=GetTagChar("CurDate");
//添加flow1
ListSubItem=ListItem->ListSubItems->add();
ListSubItem->text=GetTagChar("flow1");
//添加flow2
ListSubItem=ListItem->ListSubItems->add();
ListSubItem->text=GetTagChar("flow2");
//添加flow3
ListSubItem=ListItem->ListSubItems->add();
ListSubItem->text=GetTagChar("flow3");
rs->movenext();
}
}
if(cn->State != 0)
cn->Close;
__object_delete(obj);
__object_delete(pic);
__object_delete(pdl);
}
保存运行,就可以看到效果了。