Winform常用代码

//ToolStripSplitButton标准按钮和下拉按钮的组合,各自工作,但有联系,感觉上后者是没有向下箭头ToolStripDropDownButtonToolStripDropDownButton只含有一个按钮,可以选择有没有向下箭头的标志,单击时显示关联的 ToolStripDropDown 的控件。两者均可改变箭头标志在做还是在右。

//VS自带双缓冲

this.SetStyle(ControlStyles.UserPaint |

 ControlStyles.AllPaintingInWmPaint |

ControlStyles.OptimizedDoubleBuffer, true);

//控件双缓冲

Control.DoubleBuffered=true; //attribute modfied by Protected

//手工双缓冲

Bitmap bmp = new Bitmap(600, 600);
Graphics g = Graphics.FromImage(bmp);

g.DrawLine();

this.CreateGraphics().DrawImage(bmp, 0, 0);//这句是关键,不能à在OnPaint里画BitBmp在这里调Invalidate

Invalidate(Rectangle)//规定区域重绘,解决闪烁的另一种方法

ComboBox ComboBox1 = (ComboBox) sender;

(Sender as SomeObject).Method()

this.label1.Font = new System.Drawing.Font("微软雅黑", 72F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

this.label1.Font = new Font("微软雅黑", fontSize);

//自定义控件背景透明

SetStyle(ControlStyles.UserPaint, true);

SetStyle(ControlStyles.SupportsTransparentBackColor, true);

this.BackColor = Color.Transparent;

//获得程序集

System.Reflection.Assembly assem = System.Reflection.Assembly.GetExecutingAssembly();

//点移位

Point.Offset(Point);

Point.Offset(int,int);

Rectangle.Contains(Point);

//截获标题栏消息,自画标题栏

using System.Runtime.InteropServices;

using System.Drawing.Drawing2D;

[DllImport("user32.dll")]

private static extern IntPtr GetWindowDC(IntPtr hWnd);

[DllImport("user32.dll")]

private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);

private const int WM_NCPAINT = 0x0085;

private const int WM_NCACTIVATE = 0x0086;

private const int WM_NCLBUTTONDOWN = 0x00A1;

protected override void WndProc(ref Message m)

{

    base.WndProc(ref m);

    Rectangle vRectangle = new Rectangle((Width - 75) / 2, 3, 75, 25);

    switch (m.Msg)

    {

        case WM_NCPAINT:

        case WM_NCACTIVATE:

            IntPtr vHandle = GetWindowDC(m.HWnd);

            Graphics vGraphics = Graphics.FromHdc(vHandle);

            vGraphics.FillRectangle(new LinearGradientBrush(vRectangle, 

                Color.Pink, Color.Purple, LinearGradientMode.BackwardDiagonal),

                vRectangle);

            

            StringFormat vStringFormat = new StringFormat();

            vStringFormat.Alignment = StringAlignment.Center;

            vStringFormat.LineAlignment = StringAlignment.Center;

            vGraphics.DrawString("About", Font, Brushes.BlanchedAlmond, 

                vRectangle, vStringFormat);

            vGraphics.Dispose();

            ReleaseDC(m.HWnd, vHandle);

            break;

        case WM_NCLBUTTONDOWN:

            Point vPoint = new Point((int)m.LParam);

            vPoint.Offset(-Left, -Top);

            if (vRectangle.Contains(vPoint))

                MessageBox.Show(vPoint.ToString());

            break;

    }

}

Control.SuspendLayout;//在它和ResumeLayout之间的代码不会引起Parent Control的重绘

Control.AddRange(new Control[]{});//添加多个控件

Control.ResumeLayout;// 在它和SuspendLayout之间的代码不会引起Parent Control的重绘

Button[] buttons = new Button[] {};//大胆地设类数组吧~

Button.SetBounds(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连接字符串

@"Data Source= .\SQLEXPRESS;AttachDBFilename=C:\..\*.MDF;Integrated Security=True;User Instance=True"))

//sqlconnection连接的基本步骤

using System.Data.SqlClient;

Dataset dataset = new DataSet();

using (SqlConnection conn = new SqlConnection(@"Data Source= .\SQLEXPRESS;AttachDBFilename=C:\SQL Server 2000 Sample Databases\NORTHWND.MDF;Integrated Security=True;User Instance=True"))

{

conn.Open();

SqlDataAdapter adapter = new SqlDataAdapter(conn.CreateCommand());

    adapter.SelectCommand.CommandText = "select * from customers";

adapter.Fill(dataset);

foreach (DataRow row in dataset.Tables[0].Rows)

{

string item=row["ContactTitle"]+","+row["ContactName"];

    listBox1.Items.Add(item);

}

}

ListBox.Items.Add(new string)//ListBox添加项

//创建DataSet中的记录

DataRow row = DataSet.Tables[0].NewRow();

row["**"] =***;

dataset.Tables[0].Rows.Add(row);

//更新DataSet

DataRow row=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中彻底删除

DataRow row=DataSet.Table[0].Rows[index];

row[***]=***;

row.delete();

TYPE varable=row[***,DataRowVersion.Original]

// DataRow的完整访问方式和DataRow.RowState

Switch (row.RowState)

{

case DataRowState.Deleted:

    row["***", DataRowVersion.Original];

    case DataRowState.Added:

    row["["***"]

    case DataRowState.Modified:

    row["***", DataRowVersion.Original]

       row["***", DataRowVersion.Current]

case DataRowVersion.Unchanged:

    row["***"]

}

//获取部分特定状态的数据集

DataTable modifiedTable = DataSet.Tables[0].GetChanges(DataRowState.Added| DataRowState.Modified| DataRowState.Deleted);

//创建数据库查询连接适配器的几种方式

SqlDataAdapter  adapter = new SqlDataAdapter("select * from TABLENAME", SqlConnection); //最简单

SqlDataAdapter adapter = new SqlDataAdapter(SqlConnection.CreateCommand());

adapter.SelectCommand.CommandText = "select * from TABLENAME ";

SqlDataAdapter  adapter = new sqldat SqlDataAdapter();

adapter.SelectCommand = new SqlCommand("select * from TABLENAME ", SqlConnection);

//万能的数据集更新器SqlCommandBuilder

SqlDataAdapter adapter = new SqlDataAdapter("select * from TABLENAME ", SqlConnection);

new SqlCommandBuilder(adapter);

try

{

adapter.Update(modifiedDataSet);

PoulateListBox();

}

catch (System.Exception ex)

{

}

//多表数据集建议分别创建适配器

SqlDataAdapter  adapter1 = new SqlDataAdapter("select * from TABLENAME", SqlConnection); 

adapter1.Fill(DataSet,TABLENAME1);

SqlDataAdapter  adapter2 = new SqlDataAdapter("select * from TABLENAME", SqlConnection); 

adapter2.Fill(DataSet,TABLENAME2);

//

//Make some changes to the DataSet .TABLENAME1 or DataSet .TABLENAME2

//

new SqlCommandBuilder(adapter1);

adapter1.Update(DataSet, TABLENAME1);

new SqlCommandBuilder(adapter2);

adapter2.Update(DataSet, TABLENAME2);

//创建DataSet自带约束

UniqueConstraint constrint = new UniqueConstraint(DataTable.Columns["***"]);//唯一性约束

DataTable.Constraints.Add(constrint);

//外键约束:ForeignKeyConstraint

//关系基于两张表的两个列上,添加于两张表共属的数据集,并且自动生成分别在两个表上生成UniqueConstraint ForeignKeyConstraint

DataRelation relation = new DataRelation("CustomersOrders", DataTable.Columns["***"], DataTable.Columns["***"]);

dataset.Relations.Add(relation);

Form.Modal//判断显示方式是模式还是非模式,模式为true,非模式为false,只有在Load事件中和之后该属性才有实际意义,在构造期间默认为false

myForm.Control1.Text=Data put in by a user;//这样不好,封装性不强不易维护更新,用下面的

pulbic String Control1Text

{

get{

return Control1.Text;

}

Set{

Control1.Text;=value;

}

}

//

myForm. Control1Text= Data put in by a user;

//DialogResult res=ShowDialog()只是获取对话框结果的快捷方式,完整方式如下

void someButton_Click(object sender,EventArgs e){

this.DialogResult=DialogResult.Retry;

this.close();

}

someForm=new someForm();

someForm.showDialog();

DialogResult ref= someForm .DialogResult;

if(ref= DialogResult.Retry)

//

string path =Directory.GetCurrentDirectory();

System.IO.FileStream aFile = new System.IO.FileStream(path, FileMode.Open);

StreamReader sr = new StreamReader(aFile, System.Text.Encoding.Default);

/*

对于每个关联的 SqlConnection,一次只能打开一个 SqlDataReader

SqlConnection 与 SqlDataAdapter 和 SqlCommand 一起使用,可以在连接 Microsoft SQL Server 数据库时提高性能。

对于所有第三方 SQL 服务器产品以及其他支持 OLE DB 的数据源,请使用 OleDbConnection。

SqlConnection 超出范围,则不会将其关闭因此,必须通过调用 Close 或 Dispose 显式关闭该连接。最好在using 块内部打开连接

连接自字符串关键字不区分大小写,并将忽略键/值对之间的空格。 不过,根据数据源的不同,值可能是区分大小写的。 任何包含分号、单引号或双引号的值必须用双引号引起来。

*/

System.Data.SqlClient.SqlConnectionStringBuilder builder =new System.Data.SqlClient.SqlConnectionStringBuilder();

builder["Data Source"] = "(local)";

builder["integrated Security"] = true;

builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";

// 使用System.Data.SqlClient.SqlConnectionStringBuilder不需要担心分号、单引号或双引号的转义问题

Console.WriteLine(builder.ConnectionString);

//打开数据库的某个古老方法

SqlConnection mc=new SqlConnection();

mc.ConnectionString=/**/;

mc.Open();

//有关SqlCommand, SqlDataReader的基本使用

SqlCommand scm=SqlConnection.CreateCommand();

scm.CommandText=select */**/;

SqlDataReader sdr=scm.ExecuteReader();

sdr.Read();

//

sdr.close();

//以ToolStrip为例绘制简便背景

e.Graphics.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(

new System.Drawing.Point(0, toolStrip1.Height),

new System.Drawing.Point(0, 0), 

Color.FromKnownColor(KnownColor.ControlDark), 

Color.FromKnownColor(KnownColor.ControlLight)), 

toolStrip1.ClientRectangle);

//获取Color的几种方式

Color.FromKnownColor(KnownColor.ControlLight);

Color.FromArgb(int r,int g,int b);

Color.FromArgb(int a,int r,int b);//a表示透明度,0-255,0为全透明,255为不透明,

/*

如果安装时,改了实例名,也就是命名实例,那么客户端在连接时,要使用机器名加实例名来进行标识:计算机名\实例名。

*/

//This table shows all connection string properties for the ADO.NET SqlConnection object. Most of the properties are also used in ADO. All properties and descriptions is from msdn. 

Name

Default

Description

Application Name

 

The name of the application, or '.Net SqlClient Data Provider' if no application name is provided.

AttachDBFilename
-or-
extended properties
-or-
Initial File Name

 

The name of the primary file, including the full path name, of an attachable database. The database name must be specified with the keyword 'database'.

Connect Timeout
-or-
Connection Timeout

15

The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating an error.

Connection Lifetime

0

When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the value specified by connection lifetime. Useful in clustered configurations to force load balancing between a running server and a server just brought on-line.

Connection Reset

'true'

Determines whether the database connection is reset when being removed from the pool. Setting to 'false' avoids making an additional server round-trip when obtaining a connection, but the programmer must be aware that the connection state is not being reset.

Current Language

 

The SQL Server Language record name.

Data Source
-or-
Server
-or-
Address
-or-
Addr
-or-
Network Address

 

The name or network address of the instance of SQL Server to which to connect.

Enlist

'true'

When true, the pooler automatically enlists the connection in the creation thread's current transaction context.

Initial Catalog
-or-
Database

 

The name of the database.

Integrated Security
-or-
Trusted_Connection

'false'

Whether the connection is to be a secure connection or not. Recognized values are 'true', 'false', and 'sspi', which is equivalent to 'true'.

Max Pool Size

100

The maximum number of connections allowed in the pool.

Min Pool Size

0

The minimum number of connections allowed in the pool.

Network Library
-or-
Net

'dbmssocn'

The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpntw (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (Apple Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory) and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP). 
The corresponding network DLL must be installed on the system to which you connect. If you do not specify a network and you use a local server (for example, "." or "(local)"), shared memory is used.

Packet Size

8192

Size in bytes of the network packets used to communicate with an instance of SQL Server.

Password
-or-
Pwd

 

The password for the SQL Server account logging on.

Persist Security Info

'false'

When set to 'false', security-sensitive information, such as the password, is not returned as part of the connection if the connection is open or has ever been in an open state. Resetting the connection string resets all connection string values including the password.

Pooling

'true'

When true, the SQLConnection object is drawn from the appropriate pool, or if necessary, is created and added to the appropriate pool.

User ID

 

The SQL Server login account.

Workstation ID

the local computer name

The name of the workstation connecting to SQL Server.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


本篇内容主要讲解“sqlalchemy的常用数据类型怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“sqlalche...
今天小编给大家分享一下sqlServer实现分页查询的方式有哪些的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家
这篇文章主要介绍“sqlmap之osshell怎么使用”,在日常操作中,相信很多人在sqlmap之osshell怎么使用问题上存在疑惑,小编查阅了各式资料,整理出
本篇内容介绍了“SQL注入的知识点有哪些”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧...
1. mssql权限sa权限:数据库操作,文件管理,命令执行,注册表读取等system。是mssql的最高权限db权限:文件管理,数据库操作等 users-administratorspublic权限:数据库操作 guest-users2、sql server注入执行命令查
sql执行计划如何查看?在SPL庞大的数据中我们不知道如何查看实际数据库中发生了什么事情,有必要定期进行查询优化和索引否则会影响我们后期的SQL的查询速度。那么针对这样的问题我们必须要知道SQL执行的计划,在本文中winwin7小编给大家分享下SQL执
SQL Server 是Microsoft 公司推出的关系型数据库管理系统。具有使用方便可伸缩性好与相关软件集成程度高等优点应用非常广泛。不过在使用中,我们会遇到非常多的错误,面对这么庞大的数据库环境,当然会有精确的错误代码的对照季,下面小编分享的
SQL Server本地账户无法登陆出现错误提示:error:40-Could not open a connenction to SQL Server的问题很常见,对于初学者来说可能不知道如何解决,一起来看看下面的解决方案。解决步骤如下:1、这种情况需要开启 SQL Server service
微软推出的SQL2008是一款非常好用的数据库软件,它稳定、功能强大,为众多企业提供了最佳的数据库解决方案,那么我们如何在Windows中安装它呢,一些朋友对SQL Server 2008的安装过程还不是很熟悉,下面就一起来看看SQL Server 2008详细安装图解...
本页概要如果您使用的是 SQL Server 2005备份和还原Sp_detach_db 和 Sp_attach_db 存储过程关于排序规则的说明导入和导出数据(在 SQL Server 数据库之间复
DBCC CHECKIDENT 检查指定表的当前标识值,如有必要,还对标识值进行更正。 语法 DBCC CHECKIDENT ( 'table_name' [ , { NORESEED
这里对 SQL Server 字符串函数进行分门别类地列出,便于查阅和记忆,相信大家都在其它方面有高深的编程基础,从字面上来说大家都知道这些函数的意义,就不对这些函数作过多的解释了,主要谈些经验,具体
查询及删除重复记录的方法 1、查找表(people)中多余的重复记录,重复记录是根据单个字段(peopleId)来判断select*frompeoplewherepeopleIdin(selectpe
微软发SQL Server 2008第二个CTP预览版from: http://news.csdn.net/n/20070807/107158.html8月7日消息,微软公司本周发布了SQL Serv
症状当您将数据库备份恢复到另一台服务器时,可能会遇到孤立用户的问题。SQL Server 联机丛书中的孤立用户疑难解答主题中没有讲述解决此问题的具体步骤。本文介绍了如何解决孤立用户问题。更多信息虽然术
当登录SQL Server 2005时可能碰到错误: 'No Process is on the Other End of the Pipe'。解决方法:(1)Open up SQL
概要本文描述如何映射标准登录和集成登录来解决在运行 SQL Server 的服务器之间移动数据库时的权限问题。更多信息当您将数据库从一个运行 SQL Server 的服务器移到另一个运行 SQL Se
----------------------------------------问题:该用户与可信的SQL SERVER 连接无关联使用sa用户或自建用户使用“SQL SERVER 身份认证”连接数据
更新日期: 2007 年 5 月 20 日 使用下表可以确定各种版本的 Microsoft SQL Server 2005 支持哪些功能。有关 SQL Server 2005 Enterprise E
当从Excel导入数据到Sql Sever中,可能会出现以下问题:
对于指定的缓冲区大小而言,源列的数据太大