我C#写的WinForm公共类的方法,编程轻松简单(一)
llnet 2003-05-27 12:31:48 在编写WinForm程序时常常有很多重复的代码,这种堆积代码的程序不是好程序,灵活性差,也不方便维护,为此我写了一些常用的公共类的方法,很多操作只需要一条语句就可以实现,编程更方便,特别是一些公共变量可以放到公共类库中,运行时只需要在主程序中给其赋值,在应用的Form中来取值就可以了,比如说数据库连接串,Form大小,颜色等。
首先建一个公共的Class,我用的命名空间CTM_LIB,Class 是 PublicLib,写好公共变量和方法,执行既可生成类库(生成到一个公共文件夹),各各应用项目把该类库引用就可以。
例子很多,只能分部分介绍,大家也可不断补充,我写了如下方法:
全局公共数据库连接
获得类中错误信息接口
取得SQL数据库服务器时间 SystemDateTime()
打开数据库连接 OpenConnection()
通过Select语句返回标准数据集合 QueryDataSet()
执行标准SQL操作语句 ExecuteBySql()
将数据集合中的数据添加到ComboBox ListBox FillItemsByDataset()
初始化DataGrid,设置标题,字段宽度,把DataSet值导入DataGrid FillDataGridbyDataSet()
初始化ListView,设置标题,字段宽度,把DataSet值导入ListView FillListViewbyDataSet()
将用逗号分隔的字符串替换命令行对应位置的"?"参数 ReplateCmdByParam()
类库例子:
using System;
using System.Data;
using System.Data.OleDb;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
namespace CTM_LIB
{
/// **************************************************<br>
/// 《公共类库》<br>
/// **************************************************<br>
public class PublicLib
{
/// --------------------------------------------------
/// FillItemsByDataset()
/// --------------------------------------------------
/// 方法功能:
/// 将数据集合中的数据添加到ComboBox ListBox
/// 入口参数:
/// sender: 控件对象(ComboBox,ListBox)
/// ds:DataSet数据集(前两个字段分别为对象的DisplayMember,ValueMember对应值)
/// 出口参数:
/// 无
/// 全局变量:
/// 无
/// WEB 注释:
/// <summary>将数据集合中的数据添加到ComboBox ListBox</summary>
/// <param name="sender">控件对象(ComboBox,ListBox).</param>
/// <param name="ds">DataSet数据集(前两个字段分别为对象的DisplayMember,ValueMember对应值)</param>
/// <returns>正常装入目标控件返回 true,出错返回 false</returns>
/// <remarks></remarks>
/// --------------------------------------------------
public bool FillItemsByDataset(object sender,DataSet ds)
{
if (ds==null||ds.Tables.Count==0)
{
return false;
}
try
{
switch(sender.GetType().ToString())
{
case "System.Windows.Forms.ComboBox":
System.Windows.Forms.ComboBox cb = (System.Windows.Forms.ComboBox) sender;
cb.Items.Clear();
cb.DataSource=ds.Tables[0].DefaultView;
cb.DisplayMember=ds.Tables[0].Columns[0].ToString();
cb.ValueMember=ds.Tables[0].Columns[1].ToString();
break;
case "System.Windows.Forms.ListBox":
System.Windows.Forms.ListBox lb = (System.Windows.Forms.ListBox) sender;
lb.Items.Clear();
lb.DataSource=ds.Tables[0].DefaultView;
lb.DisplayMember=ds.Tables[0].Columns[0].ToString();
lb.ValueMember=ds.Tables[0].Columns[1].ToString();
break;
default:
break;
}
}
catch(System.Exception Err)
{
mstcErrorInfo.Description=Err.Message;
return false;
}
ds.Dispose();
return true;
}
}
应用Form中的调用:
CTM_LIB.PublicLib cc = new CTM_LIB.PublicLib();
private void form1_Load(object sender, System.EventArgs e)
{
cc.FillItemsByDataset(comboBox1,cc.QueryDataSet(strSql));
//cc.QueryDataSet(strSql) 是根据strSql语句生成的DataSet记录集
}
private void btnTest_Click(object sender, System.EventArgs e)
{
MessageBox.Show(this.comboBox1.SelectedValue.ToString()+"::"+this.comboBox1.Text.ToString());
}