技术开发 频道

.NET C/S(WinForm)开发技巧

【IT168 技术文档】
1.数据绑定。

 DataReader 读取数据,用DataTable.Load(IDataReader)方法将数据加载到 DataTable ,用DataGridView 显示输出。不要把DataGridView直接绑定到DataReader的目的是数据导出到Excel时,数据源可以再次从DataGridView获得。
   不要在 DataGridView 内编辑添加数据,因为数据类型检查不严格(或要严格检查类型需要花费更大的成本)。

2.数据导出到 Excel 。

 代码如下:
/**//// <summary> 
///
/// ** DataTable 数据导出到 Excel **
///
/// Author: 周振兴 (Zxjay 飘遥)
///
/// E-Mail: tda7264@163.com
///
/// Blog: http://blog.csdn.net/zxjay
///
/// Date: 07-08-31
///
/// </summary>
Excel.Application app = new Excel.Application();
app.Visible = false;
Excel.Workbook wb = app.Workbooks.Add(true);
Excel.Worksheet ws = (Excel.Worksheet)wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing,

Type.Missing);

DataTable dt = (DataTable)dgvClientInfo.DataSource;

for (int i = 0; i < dt.Columns.Count; i++)
...{
ws.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}

for (int j = 0; j < dt.Rows.Count; j++)
...{
for (int k = 0; k < dt.Columns.Count; k++)
...{
ws.Cells[j + 2, k + 1] = dt.Rows[j][k];
}
}
app.Visible = true;
    注意:Excel的Cells[,]下标是从1,1开始的,而不是0,0。

3.防止子窗口重复打开,确保某一子窗口只打开一次。

   代码为:

foreach (Form frm in this.MdiChildren)
...{
if (frm is WorkerList)
...{
frm.WindowState = FormWindowState.Normal;
frm.Activate();
return;
}
}

WorkerList wl = new WorkerList();
wl.MdiParent = this;
wl.Show();
4.使用枚举 enum 区分类同信息。

 硬编码方式容易造成混乱。如本系统的常用电话/常用网址,数据项都为:名称-内容-备注,可将它们保存在同一个表中,在程序中为区分信息类型,可定义以下枚举:
public enum TelWeb
...{
Telephone,WebSite
}

5.在ToolStrip中加入其它WinForm控件。   
   如在ToolStrip中加入DateTimePicker。

DateTimePicker dt1 = new DateTimePicker(); 
dt1.Width = 110;
ToolStripControlHost host1 = new ToolStripControlHost(dt1);
host1.Alignment = ToolStripItemAlignment.Right;
toolStrip1.Items.Insert(10, host1);

6.用微软的可打印的富文本框控件打印带格式的文本。

 与.NETFX自带的RichTextBox相比只增强了打印功能。通过该控件,可设置文本字体、颜色、对齐方式、粘贴图片,可打印看上去很专业的文档,截图如下:

7.保存富文本格式到数据库。

 以二进制格式保存。保存的代码为:

MemoryStream ms = new MemoryStream();
rtbContent.SaveFile(ms, RichTextBoxStreamType.RichText);
byte[] bt=ms.ToArray(); //将bt保存到数据库
读取的代码为:

byte[] bt = (byte[])SqlHelper.ExecuteScalar(sqlStr, null);
MemoryStream ms = new MemoryStream(bt, false);
rtbContent.LoadFile(ms, RichTextBoxStreamType.RichText);
   在SQLServer中对应的数据类型为:image

0
相关文章