GridView控件,用表格的形式将数据显示出来。那么如何将将数据绑定到GridView中呢?目前值学习了两种,一种是直接绑定数据源,另一种是动态显示数据(主要使用对象有SqlCommand,SqlDataAdapter,DateSet)。这里主要说一下后一种方法:
private void showData(String sql) { try { //自动生成表头 this.gridSend.AutoGenerateColumns = true; //这个属性是当你点击GridView中任意一个单元格时,默认选中该单元格所在行 this.gridSend.SelectionMode = DataGridViewSelectionMode.FullRowSelect; //简单的数据库连接 SqlConnection conn = new SqlConnection("server=.\\sqlexpress;database=dodoo2;uid=s1;pwd=s1"); conn.Open(); SqlCommand cmd = new SqlCommand(); SqlDataAdapter da = new SqlDataAdapter(); cmd.Connection = conn; cmd.CommandText = sql; cmd.CommandType = CommandType.Text; da.SelectCommand = cmd; DataSet ds = new DataSet(); da.Fill(ds, "lb_billflow"); this.gridSend.DataSource = ds.Tables[0]; conn.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message+sqlSel); } }
显示出数据后,通过CellClick()事件,获取选中行的数据,例如获取选中行中的id值:
int id = Convert.ToInt16(gridSend.CurrentRow.Cell["ID"].value);
因为在做报表,还需要将GridView打印成报表。这里我用的是GridReport工具,这里边提供了丰富的功能。可以直接做出现成的报表,在页面通过GridReport.start()显示,也可以通过编码将GridView中的值传如报表中。还是介绍后一种方法:
private void ReportFetchRecord() { for (int row = 0; row < gridSend.RowCount;++row ) { Report.DetailGrid.Recordset.Append(); //for循环中ColumnCount-1!如果没有-1,会抛出 for (int col = 0; col < gridSend.ColumnCount-1; ++col) Report.DetailGrid.Recordset.Fields[col + 1].AsString = gridSend.Rows[r ow].Cells[col].Value.ToString(); Report.DetailGrid.Recordset.Post(); } } private void DefineReport() { Report.Clear();//清空报表 Report.Printer.PaperOrientation = GRPaperOrientation.grpoLandscape; //定义表头 IGRReportHeader Reportheader = Report.InsertReportHeader(); Reportheader.Height = 1.38; //插入一个静态文本框,显示报表标题文字 IGRStaticBox StaticBox = Reportheader.Controls.Add(GRControlType.grctStaticBox).AsStaticBox; StaticBox.Text = "发放物品清单"; StaticBox.Font.Point = 15; StaticBox.Font.Bold = true; StaticBox.Top = 0.40; StaticBox.Width = 5.64; StaticBox.Height = 0.58; //根据Gridview的列信息定义明细网络 Report.InsertDetailGrid(); Report.DetailGrid.ColumnTitle.Height = 0.58; Report.DetailGrid.ColumnContent.Height = 0.58; //将数据写入报表中 IGRRecordset RecordSet = Report.DetailGrid.Recordset; for (int i = 0; i < gridSend.ColumnCount;++i ) { string ColumnName = gridSend.Columns[i].Name; RecordSet.AddField(ColumnName,GRFieldType.grftString); double ReportColumnWidth = Convert.ToDouble(gridSend.Columns[i].Width)/50; Report.DetailGrid.AddColumn(ColumnName,gridSend.Columns[i].HeaderText,ColumnName,ReportColumnWidth); } } 窗体的构造函数中添加: Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecord); 报表的打印预览功能:Report.PrintPreview(true);