c#WinForm常用代码.docx
《c#WinForm常用代码.docx》由会员分享,可在线阅读,更多相关《c#WinForm常用代码.docx(12页珍藏版)》请在冰豆网上搜索。
c#WinForm常用代码
//ToolStripSplitButton是标准按钮和下拉按钮的组合,各自工作,但有联系,感觉上后者是没有向下箭头ToolStripDropDownButton;ToolStripDropDownButton只含有一个按钮,可以选择有没有向下箭头的标志,单击时显示关联的 ToolStripDropDown 的控件。
两者均可改变箭头标志在做还是在右。
.
//VS自带双缓冲
this.SetStyle(ControlStyles.UserPaint|
ControlStyles.AllPaintingInWmPaint|
ControlStyles.OptimizedDoubleBuffer,true);
//控件双缓冲
Control.DoubleBuffered=true;//attributemodfiedbyProtected
//手工双缓冲
Bitmapbmp=newBitmap(600,600);
Graphicsg=Graphics.FromImage(bmp);
g.DrawLine();
this.CreateGraphics().DrawImage(bmp,0,0);//这句是关键,不能在OnPaint里画BitBmp在这里调Invalidate
Invalidate(Rectangle)//规定区域重绘,解决闪烁的另一种方法
ComboBoxComboBox1=(ComboBox)sender;
(SenderasSomeObject).Method()
this.label1.Font=newSystem.Drawing.Font("微软雅黑",72F,System.Drawing.FontStyle.Regular,System.Drawing.GraphicsUnit.Point,((byte)(134)));
this.label1.Font=newFont("微软雅黑",fontSize);
//自定义控件背景透明
SetStyle(ControlStyles.UserPaint,true);
SetStyle(ControlStyles.SupportsTransparentBackColor,true);
this.BackColor=Color.Transparent;
//获得程序集
System.Reflection.Assemblyassem=System.Reflection.Assembly.GetExecutingAssembly();
//点移位
Point.Offset(Point);
Point.Offset(int,int);
Rectangle.Contains(Point);
//截获标题栏消息,自画标题栏
usingSystem.Runtime.InteropServices;
usingSystem.Drawing.Drawing2D;
[DllImport("user32.dll")]
privatestaticexternIntPtrGetWindowDC(IntPtrhWnd);
[DllImport("user32.dll")]
privatestaticexternintReleaseDC(IntPtrhWnd,IntPtrhDC);
privateconstintWM_NCPAINT=0x0085;
privateconstintWM_NCACTIVATE=0x0086;
privateconstintWM_NCLBUTTONDOWN=0x00A1;
protectedoverridevoidWndProc(refMessagem)
{
base.WndProc(refm);
RectanglevRectangle=newRectangle((Width-75)/2,3,75,25);
switch(m.Msg)
{
caseWM_NCPAINT:
caseWM_NCACTIVATE:
IntPtrvHandle=GetWindowDC(m.HWnd);
GraphicsvGraphics=Graphics.FromHdc(vHandle);
vGraphics.FillRectangle(newLinearGradientBrush(vRectangle,
Color.Pink,Color.Purple,LinearGradientMode.BackwardDiagonal),
vRectangle);
StringFormatvStringFormat=newStringFormat();
vStringFormat.Alignment=StringAlignment.Center;
vStringFormat.LineAlignment=StringAlignment.Center;
vGraphics.DrawString("About",Font,Brushes.BlanchedAlmond,
vRectangle,vStringFormat);
vGraphics.Dispose();
ReleaseDC(m.HWnd,vHandle);
break;
caseWM_NCLBUTTONDOWN:
PointvPoint=newPoint((int)m.LParam);
vPoint.Offset(-Left,-Top);
if(vRectangle.Contains(vPoint))
MessageBox.Show(vPoint.ToString());
break;
}
}
Control.SuspendLayout;//在它和ResumeLayout之间的代码不会引起ParentControl的重绘
Control.AddRange(newControl[]{});//添加多个控件
Control.ResumeLayout;//在它和SuspendLayout之间的代码不会引起ParentControl的重绘
Button[]buttons=newButton[]{};//大胆地设类数组吧~
Button.SetBounds(int,int,int,int);//设置Button的左、右、宽、高;
//应该尽可能地用Anchor、Dock,特殊情况下用Layout事件
Form.MdiParent=(Form);//设置MDI父窗口
//Active事件里this.Hide()是正道
Form.Show();
Form.Text=”Mytext”;//这两句的顺序不能
//static不能修饰临时变量,一般用来修饰类变量(不是类的对象实例变量!
!
!
)
Form.MdiParent=this;
Form.TopLevel=true;
Form.IsMdiContainer=true;
Form.ActivateMdiChild
//sqlconnection连接字符串
@"DataSource=.\SQLEXPRESS;AttachDBFilename=C:
\..\*.MDF;IntegratedSecurity=True;UserInstance=True"))
//sqlconnection连接的基本步骤
usingSystem.Data.SqlClient;
Datasetdataset=newDataSet();
using(SqlConnectionconn=newSqlConnection(@"DataSource=.\SQLEXPRESS;AttachDBFilename=C:
\SQLServer2000SampleDatabases\NORTHWND.MDF;IntegratedSecurity=True;UserInstance=True"))
{
conn.Open();
SqlDataAdapteradapter=newSqlDataAdapter(conn.CreateCommand());
adapter.SelectCommand.CommandText="select*fromcustomers";
adapter.Fill(dataset);
foreach(DataRowrowindataset.Tables[0].Rows)
{
stringitem=row["ContactTitle"]+","+row["ContactName"];
listBox1.Items.Add(item);
}
}
ListBox.Items.Add(newstring)//ListBox添加项
//创建DataSet中的记录
DataRowrow=DataSet.Tables[0].NewRow();
row["**"]=***;
dataset.Tables[0].Rows.Add(row);
//更新DataSet
DataRowrow=DataSet.Table[0].Rows[index];
row[“***”]=***;
//删除DataSet中的记录
DataSet.Tables[0].Rows.Remove(DataSet.Table[0].Rows[index]);
//DataRow.Delete()和DataSet.Tables[0].Rows.Remove()不一样,后者是从DataSet中彻底删除
DataRowrow=DataSet.Table[0].Rows[index];
row[“***”]=***;
row.delete();
TYPEvarable=row[“***”,DataRowVersion.Original]
//DataRow的完整访问方式和DataRow.RowState
Switch(row.RowState)
{
caseDataRowState.Deleted:
row["***",DataRowVersion.Original];
caseDataRowState.Added:
row["["***"]
caseDataRowState.Modified:
row["***",DataRowVersion.Original]
row["***",DataRowVersion.Current]
caseDataRowVersion.Unchanged:
row["***"]
}
//获取部分特定状态的数据集
DataTablemodifiedTable=DataSet.Tables[0].GetChanges(DataRowState.Added|DataRowState.Modified|DataRowState.Deleted);
//创建数据库查询连接适配器的几种方式
SqlDataAdapteradapter=newSqlDataAdapter("select*fromTABLENAME",SqlConnection);//最简单
SqlDataAdapteradapter=newSqlDataAdapter(SqlConnection.CreateCommand());
adapter.SelectCommand.CommandText="select*fromTABLENAME";
SqlDataAdapteradapter=newsqldatSqlDataAdapter();
adapter.SelectCommand=newSqlCommand("select*fromTABLENAME",SqlConnection);
//万能的数据集更新器SqlCommandBuilder
SqlDataAdapteradapter=newSqlDataAdapter("select*fromTABLENAME",SqlConnection);
newSqlCommandBuilder(adapter);
try
{
adapter.Update(modifiedDataSet);
PoulateListBox();
}
catch(System.Exceptionex)
{
}
//多表数据集建议分别创建适配器
SqlDataAdapteradapter1=newSqlDataAdapter("select*fromTABLENAME",SqlConnection);
adapter1.Fill(DataSet,”TABLENAME1”);
SqlDataAdapteradapter2=newSqlDataAdapter("select*fromTABLENAME",SqlConnection);
adapter2.Fill(DataSet,”TABLENAME2”);
//
//MakesomechangestotheDataSet.TABLENAME1orDataSet.TABLENAME2
//
newSqlCommandBuilder(adapter1);
adapter1.Update(DataSet,”TABLENAME1”);
newSqlCommandBuilder(adapter2);
adapter2.Update(DataSet,”TABLENAME2”);
//创建DataSet自带约束
UniqueConstraintconstrint=newUniqueConstraint(DataTable.Columns["***"]);//唯一性约束
DataTable.Constraints.Add(constrint);
//外键约束:
ForeignKeyConstraint
//关系基于两张表的两个列上,添加于两张表共属的数据集,并且自动生成分别在两个表上生成UniqueConstraint和ForeignKeyConstraint
DataRelationrelation=newDataRelation("CustomersOrders",DataTable.Columns["***"],DataTable.Columns["***"]);
dataset.Relations.Add(relation);
Form.Modal//判断显示方式是模式还是非模式,模式为true,非模式为false,只有在Load事件中和之后该属性才有实际意义,在构造期间默认为false
myForm.Control1.Text=”Dataputinbyauser”;//这样不好,封装性不强不易维护更新,用下面的
pulbicStringControl1Text
{
get{
returnControl1.Text;
}
Set{
Control1.Text;=value;
}
}
//…
myForm.Control1Text=”Dataputinbyauser”;
//DialogResultres=ShowDialog()只是获取对话框结果的快捷方式,完整方式如下
voidsomeButton_Click(objectsender,EventArgse){
this.DialogResult=DialogResult.Retry;
this.close();
}
someForm=newsomeForm();
someForm.showDialog();
DialogResultref=someForm.DialogResult;
if(ref=DialogResult.Retry)
//…
stringpath=Directory.GetCurrentDirectory();
System.IO.FileStreamaFile=newSystem.IO.FileStream(path,FileMode.Open);
StreamReadersr=newStreamReader(aFile,System.Text.Encoding.Default);
/*
对于每个关联的SqlConnection,一次只能打开一个SqlDataReader
SqlConnection与SqlDataAdapter和SqlCommand一起使用,可以在连接MicrosoftSQLServer数据库时提高性能。
对于所有第三方SQL服务器产品以及其他支持OLEDB的数据源,请使用OleDbConnection。
SqlConnection超出范围,则不会将其关闭。
因此,必须通过调用Close或Dispose显式关闭该连接。
最好在using块内部打开连接。
连接自字符串关键字不区分大小写,并将忽略键/值对之间的空格。
不过,根据数据源的不同,值可能是区分大小写的。
任何包含分号、单引号或双引号的值必须用双引号引起来。
*/
System.Data.SqlClient.SqlConnectionStringBuilderbuilder=newSystem.Data.SqlClient.SqlConnectionStringBuilder();
builder["DataSource"]="(local)";
builder["integratedSecurity"]=true;
builder["InitialCatalog"]="AdventureWorks;NewValue=Bad";
//使用System.Data.SqlClient.SqlConnectionStringBuilder不需要担心分号、单引号或双引号的转义问题
Console.WriteLine(builder.ConnectionString);
//打开数据库的某个古老方法
SqlConnectionmc=newSqlConnection();
mc.ConnectionString=”/*…*/”;
mc.Open();
//有关SqlCommand,SqlDataReader的基本使用
SqlCommandscm=SqlConnection.CreateCommand();
scm.CommandText=”select*/*…*/”;
SqlDataReadersdr=scm.ExecuteReader();
sdr.Read();
//…
sdr.close();
//以ToolStrip为例绘制简便背景
e.Graphics.FillRectangle(newSystem.Drawing.Drawing2D.LinearGradientBrush(
newSystem.Drawing.Point(0,toolStrip1.Height),
newSystem.Drawing.Point(0,0),
Color.FromKnownColor(KnownColor.ControlDark),
Color.FromKnownColor(KnownColor.ControlLight)),
toolStrip1.ClientRectangle);
//获取Color的几种方式
Color.FromKnownColor(KnownColor.ControlLight);
Color.FromArgb(intr,intg,intb);
Color.FromArgb(inta,intr,intg,intb);//a表示透明度,0-255,0为全透明,255为不透明,
/*
如果安装时,改了实例名,也就是命名实例,那么客户端在连接时,要使用机器名加实例名来进行标识:
计算机名\实例名。
*/
//ThistableshowsallconnectionstringpropertiesfortheADO.NETSqlConnectionobject.MostofthepropertiesarealsousedinADO.Allpropertiesanddescriptionsisfrommsdn.
Name
Default
Description
ApplicationName
Thenameoftheapplication,or'.NetSqlClientDataProvider'ifnoapplicationnameisprovided.
AttachDBFilename
-or-
extended properties
-or-
InitialFileName
Thenameoftheprimaryfile,includingthefullpathname,ofanattachabledatabase.Thedatabasenamemustbespecifiedwiththekeyword'database'.
ConnectTimeout
-or-
ConnectionTimeout
15
Thelengthoftime(inseconds)towaitforaconnectiontotheserverbeforeterminatingtheattemptandgeneratinganerror.
ConnectionLifetime
0
Whenaconnectionisreturnedtothepool,itscreationtimeiscomparedwiththecurrenttime,andtheconnectionisdestroyedifthattimespan(inseconds)exceedsthevaluespecifiedbyconnectionlifetime.Usefulinclusteredconfigurationstoforceloadbalancingbetweenarunningserverandaserverjustbroughton-line.
ConnectionReset
'true'
Determineswhetherthedatabaseconnectionisresetw