2010年12月7日 星期二

DataRelation 運用(datatable)

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
DataTable coustomertable = new DataTable("Customer");
coustomertable.Columns.Add("CustomerID",typeof (int));
coustomertable.Columns.Add("Name");
coustomertable.Columns.Add("TelePhone");
coustomertable.Columns.Add("Address");

//
DataRow cRow1 = coustomertable.NewRow() ;
cRow1[0] = 101;
cRow1[1] = "王为";
cRow1[2] = "0208344569";
cRow1[3] = "北京";
coustomertable.Rows.Add(cRow1 );

DataRow cRow2 = coustomertable.NewRow();
cRow2[0] = 102;
cRow2[1] = "李力";
cRow2[2] = "07568524456";
cRow2[3] = "广州";
coustomertable.Rows.Add(cRow2);

DataRow cRow3 = coustomertable.NewRow();
cRow3[0] = 103;
cRow3[1] = "胡总";
cRow3[2] = "0734810235";
cRow3[3] = "长沙";
coustomertable.Rows.Add(cRow3);


//
DataTable Orderstable = new DataTable("Orderstable");
Orderstable.Columns.Add("OrdersID",typeof (int ));
Orderstable.Columns.Add("CustomerID",typeof (int));
Orderstable.Columns.Add("Prices",typeof (int));
Orderstable.Columns.Add("ProduceName");

DataRow orow1 = Orderstable .NewRow ();
orow1[0] = 1;
orow1[1] = 101;
orow1[2] = 1500;
orow1[3] = "洗衣机";
Orderstable.Rows.Add(orow1 );

DataRow orow2 = Orderstable.NewRow();
orow2[0] = 2;
orow2[1] = 101;
orow2[2] = 2800;
orow2[3] = "冰箱";
Orderstable.Rows.Add(orow2);

DataRow orow3 = Orderstable.NewRow();
orow3[0] = 3;
orow3[1] = 102;
orow3[2] = 2000;
orow3[3] = "电视机";
Orderstable.Rows.Add(orow3);

DataRow orow4 = Orderstable.NewRow();
orow4[0] = 4;
orow4[1] = 101;
orow4[2] = 600;
orow4[3] = "电风扇";
Orderstable.Rows.Add(orow4);

DataRow orow5 = Orderstable.NewRow();
orow5[0] = 5;
orow5[1] = 102;
orow5[2] = 1000;
orow5[3] = "微波炉";
Orderstable.Rows.Add(orow5);

DataSet dataSet = new DataSet();
dataSet.Tables.Add(coustomertable );
dataSet.Tables.Add(Orderstable );

DataRelation coRelation=new DataRelation(" Customertoorders",coustomertable .Columns[0],Orderstable .Columns ["CustomerID"]);
dataSet.Relations.Add(coRelation );


foreach (DataRow row in coustomertable .Rows )
{
Console.WriteLine(row [1]+"`````````");
foreach (DataRow row1 in row.GetChildRows(coRelation ))
{
for (int i = 0; i < Orderstable.Columns.Count; i++)
{
Console.Write(row1[i] + " ");

}
Console.WriteLine();
}

}
Console.Read();
}
}
}

c# 簡單的列印程序

using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;

class MyForm : Form
{
private Button button1;
private Font myFont;
private StreamReader read;
public MyForm()
{
button1 = new Button();
button1.Text = "打印";
button1.Location = new Point(10, 10);
button1.Size = new Size(80, 40);
button1.Click+=new EventHandler(button1_Click);
this.Controls.Add(button1);
}
private void button1_Click(object o, EventArgs eg)
{
read = new StreamReader("e:\\abc.txt");
PrintDocument dc = new PrintDocument();
dc.BeginPrint+=new PrintEventHandler(dc_BeginPrint);
dc.EndPrint+=new PrintEventHandler(dc_EndPrint);
dc.PrintPage+=new PrintPageEventHandler(dc_PrintPage);
dc.QueryPageSettings+=new QueryPageSettingsEventHandler(dc_QueryPageSettings);
dc.Print();
}
private void dc_BeginPrint(Object o,PrintEventArgs eg)
{
MessageBox.Show("BeginPrint");
}
private void dc_EndPrint(object o, PrintEventArgs eg)
{
read.Dispose();
MessageBox.Show("EndPrint");
}
private void dc_PrintPage(object o, PrintPageEventArgs eg)
{
try
{
myFont = new Font("Arial", 100);

float left = eg.MarginBounds.Left;//左边距
float top = eg.MarginBounds.Top;//上边距
float linesPerPage = eg.MarginBounds.Height / myFont.GetHeight(eg.Graphics);//每页能打印的总行数
int lines = 0;//记数器,记录已打印的行数
string TextLine = read.ReadLine();//将要打印的行内容
float yPos = 0;
while(TextLine!=null && lines {
yPos = top + lines * myFont.GetHeight(eg.Graphics);//垂直位置
eg.Graphics.DrawString(TextLine, myFont, Brushes.Black, left, yPos);
//绘制文本
TextLine = read.ReadLine();//读取下一行内容;
lines++;
}//对一页的每一行进行打印;
if (TextLine != null)
eg.HasMorePages = true;
else
eg.HasMorePages = false;
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{

}
}
private void dc_QueryPageSettings(object o, PrintEventArgs eg)
{
MessageBox.Show("QueryPageSetting");
}
}

class pragrame
{

public static void Main()
{
MyForm form = new MyForm();
form.ShowDialog();
}
}

vb.net 序列化與反序列化實例

Imports System.Xml.Serialization
Imports System.Runtime.Serialization
Imports System.IO
Module Module2
Public Sub saveFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim streamw As StreamWriter = New StreamWriter(filestream)
Dim stu As New Student(1, "唐伯虎", 96)
Dim ser As XmlSerializer = New XmlSerializer(GetType(Student))

ser.Serialize(streamw, stu)

streamw.Close()
filestream.Close()
Console.WriteLine("序列化完成!")
Console.ReadLine()


End Sub

Public Sub openFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.Open, FileAccess.Read)
Dim streamr As StreamReader = New StreamReader(filename)
Dim dser As XmlSerializer = New XmlSerializer(GetType(Student))
Dim stu As Student = CType(dser.Deserialize(streamr), Student)
Console.WriteLine("文件已經打開")
System.Threading.Thread.Sleep(1000)
Console.WriteLine(stu.Sid.ToString())
Console.WriteLine(stu.Sname)
Console.WriteLine(stu.Score.ToString())
Console.ReadLine()

End Sub

Public Sub binarySaveFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim streamw As StreamWriter = New StreamWriter(filestream)
Dim stu As New Student()
With stu
.Sid = 2
.Sname = "祝枝山"
.Score = 97
End With
Dim binaryser As Formatters.Binary.BinaryFormatter = New Formatters.Binary.BinaryFormatter()
binaryser.Serialize(filestream, stu)
Console.WriteLine("序列化完成!")
Console.ReadLine()

End Sub

Public Sub binaryOpenFile(ByVal filename As String)
Dim filestream As FileStream = New FileStream(AppDomain.CurrentDomain.BaseDirectory & filename, FileMode.Open, FileAccess.Read, FileShare.Read)
Dim stu As New Student
Dim binaryDser As Formatters.Binary.BinaryFormatter = New Formatters.Binary.BinaryFormatter()
stu = binaryDser.Deserialize(filestream)
Console.WriteLine("反序列化完成")
System.Threading.Thread.Sleep(1000)
Console.WriteLine(stu.Sid.ToString())
Console.WriteLine(stu.Sname)
Console.WriteLine(stu.Score)
Console.ReadLine()
End Sub
Public Sub Main()
'saveFile("sample.txt")
'openFile("sample.txt")
'binarySaveFile("sample.txt")
binaryOpenFile("sample.txt")
End Sub
End Module

vb.net xml操作實例

Imports System.Xml
Module Module1

Sub Main()
Dim xmlDocument As Xml.XmlDocument = New XmlDocument()
xmlDocument.Load("Student.xml")
Dim xmlnode As XmlNode
xmlnode = xmlDocument.DocumentElement

Dim xmlnode1 As XmlNode = xmlnode.SelectSingleNode("student/sname")
Console.WriteLine(xmlnode1.InnerText)
Dim xmlnode2 As XmlNodeList = xmlnode.SelectNodes("student")
Dim xn As XmlNode
For Each xn In xmlnode2
Console.WriteLine(xn.InnerText)
Next
Dim xmlnode3 As XmlElement = xmlDocument.createElement_x("student")
xmlnode3.SetAttribute("firstname", "張")
xmlnode3.SetAttribute("lastname", "無忌")
Dim node1 As XmlElement = xmlDocument.createElement_x("sid")
node1.InnerText = "005"
xmlnode3.AppendChild(node1)
Dim node2 As XmlElement = xmlDocument.createElement_x("sname")
node2.InnerText = "趙敏"
xmlnode3.AppendChild(node1)
Dim node3 As XmlElement = xmlDocument.createElement_x("score")
node3.InnerText = "78"
xmlnode3.AppendChild(node1)
xmlnode3.AppendChild(node2)
xmlnode3.AppendChild(node3)
xmlnode.AppendChild(xmlnode3)
xmlDocument.Save("Student.xml")
Console.WriteLine("節點添加完成!")
Dim ndlist As XmlNodeList = xmlDocument.SelectSingleNode("Students").ChildNodes
For Each nd As XmlNode In ndlist
Dim xe As XmlElement
xe = CType(nd, XmlElement)

If xe.GetAttribute("lastname") = "無忌" Then
xe.SetAttribute("firstname", "謝")


End If


If xe.ChildNodes(0).InnerText = "005" Then
nd.RemoveChild(xe.ChildNodes(1))
xmlnode.RemoveChild(nd)
Console.WriteLine("修改完成!")
Else
Console.WriteLine("沒有找到相關節點")
End If



xe.RemoveAll()




xmlDocument.Save("Student.xml")
Next
Console.WriteLine(xmlnode3.GetAttribute("lastname"))
Console.ReadLine()

End Sub

End Module

vb.net文件操作

Imports System.IO Imports System.Threading Imports Enpot Module SetTest Private Const FileName As String = "config.txt" Public Sub drawException(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("this is a wrong") End Sub Public Sub Main() 'Dim draw As New Draw() 'draw.Name = "hutinghu" 'draw.Money = 1000 'AddHandler draw.DrawEvent, AddressOf drawException 'draw.PlayMoney() 'Console.ReadLine() If File.Exists(AppDomain.CurrentDomain.BaseDirectory + FileName) Then Console.WriteLine("開始讀取文件·······") Thread.Sleep(1000) readFile() Console.WriteLine("讀取完成,按Enter鍵退出·······") Console.ReadLine() Else Dim file As FileStream file = New FileStream(AppDomain.CurrentDomain.BaseDirectory + FileName, FileMode.Create, FileAccess.ReadWrite) Console.WriteLine("文件已經創建完成!") file.Close() Thread.Sleep(1000) Console.WriteLine("開始寫入文件·····") Thread.Sleep(1000) writeFile("Data Source=DELTA-BC6C5F378\SQLEXPRESS;Initial Catalog=hth_DB;Integrated Security=True") ' writeFile("Data Source=DELTA-BC6C5F378;Initial Catalog=_DB;Integrated Security=e") Console.Write("寫入完成,按Enter鍵退出·······") Console.ReadLine() End If End Sub Public Sub readFile() Dim streamRead As New StreamReader(AppDomain.CurrentDomain.BaseDirectory + FileName) Dim strread As String = Enpot.PC.Encrypt.Decrypt(streamRead.ReadLine()) Dim temp() As String = strread.Split(";") Dim strtemp() As String For index As Integer = 0 To temp.Length - 1 strtemp = temp(index).Split("=") Console.WriteLine(strtemp(1)) Next ' Console.ReadLine() 'strread = streamRead.ReadLine 'temp = strread.Split(";") 'For index As Integer = 0 To temp.Length - 1 ' strtemp = temp(index).Split("=") ' Console.WriteLine(strtemp(1)) 'Next streamRead.Close() End Sub Public Sub writeFile(ByVal str As String) If File.Exists(AppDomain.CurrentDomain.BaseDirectory + FileName) Then Dim write As New StreamWriter(AppDomain.CurrentDomain.BaseDirectory + FileName) write.WriteLine(Enpot.PC.Encrypt.Encrypt(str)) write.Close() Console.WriteLine("文件已經寫入!按Enter鍵退出·······") Console.ReadLine() End If End Sub End Module

vb.net 帶有事件的類的編寫

Public Class Draw ''' ''' 卡號 ''' ''' Private _id As Integer Public Property CardID() As Integer Get Return Me._id End Get Set(ByVal value As Integer) Me._id = value End Set End Property ''' ''' 姓名 ''' ''' Private _name As String Public Property Name() As String Get Return _name End Get Set(ByVal value As String) Me._name = value End Set End Property ''' ''' 金額 ''' ''' Private _money As Double Public Property Money() As Double Get Return Me._money End Get Set(ByVal value As Double) Me._money = value End Set End Property ''事件申明 Public Event DrawEvent(ByVal sender As Object, ByVal e As EventArgs) Public Sub PlayMoney() ' Console.WriteLine(Me.CardID.ToString()) If (CStr(Me.CardID)).Length = 1 Then RaiseEvent DrawEvent(Me, Nothing) ''觸發事件 Console.ReadLine() Else Console.WriteLine("{0}的錢是:{1}", Me.Name, Me.Money) End If End Sub End Class Public Class Test Public Sub drawException(ByVal sender As Object, ByVal e As EventArgs) Console.WriteLine("this is a wrong") End Sub Public Sub Main() Dim draw As New Draw() draw.Name = "hutinghu" draw.Money = 1000 AddHandler draw.DrawEvent, AddressOf drawException ''調用事件及綁定事件方法 draw.PlayMoney() Console.ReadLine() End Sub End Class

vbnet socket 實例

服务端
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text
Public Class Form1
Dim s As Socket
Dim t As Thread

Delegate Sub setTextGetBack(ByVal arg1 As Integer, ByVal arg2 As Byte()) ''声明委托,异步调用

Private Sub setText(ByVal arg1 As Integer, ByVal arg2 As Byte())
If Me.ListBox1.InvokeRequired Then
Dim stg As setTextGetBack = New setTextGetBack(AddressOf setText)
Me.Invoke(stg, New Object() {arg1, arg2})
Else
Me.ListBox1.Items.Insert(arg1, Encoding.Unicode.GetString(arg2))
End If

End Sub

Public Sub waitData()
s = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) '‘声明一个socket,使用tcp协议
Dim localEndPoint As New IPEndPoint(IPAddress.Parse("172.17.53.90"), 1024)
s.Bind(localEndPoint) '‘绑定到一台服务器
s.Listen(100) '‘侦听,最多可以侦听100连接

While True
Dim bytes(1024) As Byte '‘用来存储接收的数据字节
Dim ss As Socket = s.Accept() '‘若接收到,则创建一个新的socket与之连接
ss.Receive(bytes) '‘接收数据
setText(0, bytes) '‘处理接收到的数据
End While

End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
t = New Thread(AddressOf waitData)
t.Start()
Dim bytes(1024) As Byte
bytes = Encoding.Unicode.GetBytes("~~~~~~~~~~~~~~~~服务器开始启动~~~~~~~~~~~~~~~~")
Button1.Enabled = False
setText(0, bytes)
Try


's.Close()
't.Abort()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "错误提示")
Finally

End Try
End Sub

Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
Try

Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "错误提示")
Finally
s.Close() '‘关闭socket
t.Abort() ''中止线程
End Try
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
s.Close()
t.Abort()
Button1.Enabled = True
Button2.Enabled = False
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "错误提示")
End Try

End Sub
End Class


客户端
Imports System.Threading
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim s As Socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim endPint As IPEndPoint = New IPEndPoint(IPAddress.Parse("172.17.53.90"), 1024)
s.Connect(endPint)
s.Send(Encoding.Unicode.GetBytes(TextBox1.Text))
s.Close()
Catch ex As Exception

End Try
End Sub
End Class

vbnet socket 傳送文件

服务端:
Imports System.Text '
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Public Class Form1
Dim socket As Socket
Delegate Sub setText(ByVal text As String)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
socket = New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim localEndPoint As New IPEndPoint(Net.IPAddress.Parse("172.17.53.90"), 9999)
socket.Bind(localEndPoint)
socket.Listen(3)
SetLableText("~~~~~~~~~~~~服务已开始启动~~~~~~~~~~~~~~")
While True
Dim fileStream As FileStream = New FileStream("mytest.doc", FileMode.OpenOrCreate, FileAccess.ReadWrite)
Dim byteArray(6553500) As Byte
Dim binary As New BinaryWriter(fileStream)
Dim receiveSocket As Socket = socket.Accept()
receiveSocket.Receive(byteArray)
binary.Write(byteArray, 0, byteArray.Length - 1)
receiveSocket.Shutdown(SocketShutdown.Receive)
FileStream.Close()
receiveSocket.Close()
End While


End Sub
Private Sub SetLableText(ByVal txt As String)

If Label1.InvokeRequired Then
Dim st As setText = New setText(AddressOf SetLableText)
Me.Invoke(st, New Object() {txt})
Else
Label1.Text = txt
End If

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Label1.Text = "淡淡的"
End Sub
End Class
客户端:
Imports System.Text
Imports System.Net.Sockets
Imports System.Net
Imports System.IO
Public Class Form1
Dim fileName = ""
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
OpenFileDialog1.Filter = "All Documents(*.*)|*.*|Word Documents|*.doc"
OpenFileDialog1.FilterIndex = 1
OpenFileDialog1.RestoreDirectory = True
OpenFileDialog1.InitialDirectory = "c:\"

If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
fileName = OpenFileDialog1.FileName
End If
TextBox1.Text = fileName
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim sendSocket As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
Dim endPoint As New IPEndPoint(Net.IPAddress.Parse("172.17.53.90"), 9999)
sendSocket.Connect(endPoint)
Dim file As FileStream = New FileStream(TextBox1.Text, FileMode.Open)
Dim binaryRead As New BinaryReader(file)
Dim byteArray(file.Length - 1) As Byte
binaryRead.Read(byteArray, 0, file.Length - 1)
sendSocket.Send(byteArray)
file.Close()
sendSocket.Shutdown(SocketShutdown.Send)
sendSocket.Close()
Label2.Text = "文档已经创送完毕!"
End Sub
End Class